rayan carlon rayan carlon - 1 month ago 11
Java Question

Convert bytecode type to java type

I want to convert bytecode type to java using an api instead of manually coding for it, Is there any api for that? Since the requirement goes high I have to keep adding the convertion type manually which is bit tedious.

[Ljava/lang/StackTraceElement;
J[Ljava/lang/StackTraceElement;
Ljava/util/Map;
Ljava/util/LinkedList;
Ljava/lang/String;
Ljava/net/URL;
Z
Ljava/lang/String;
[Ljava/net/URL;


Previously I used code it manually as below.

private static Type getType(final char[] buf, final int off) {
int len;
switch (buf[off]) {
case 'V':
return VOID_TYPE;
case 'Z':
return BOOLEAN_TYPE;
case 'C':
return CHAR_TYPE;
case 'B':
return BYTE_TYPE;
case 'S':
return SHORT_TYPE;
case 'I':
return INT_TYPE;
case 'F':
return FLOAT_TYPE;
case 'J':
return LONG_TYPE;
case 'D':
return DOUBLE_TYPE;
}
}


And when I used asm library for this,

Type.getArgumentTypes(desc);


it showed me an error as below.


Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 44
at org.objectweb.asm.Type.getArgumentTypes(Unknown Source)

Answer Source

If you are using asm it would be like this,

Type.getType(desc).getClassName();

Type class from asm library and its static method getType which accepts a string will convert bytecode type to java type.