The field and method descriptors are used by the runtime for linking classes. Consequently, they should be available through reflection. I need them for creating java classes at runtime. Is the only way to reconstruct the descriptors based on the information obtained through methods like Class.getName(), which returns almost, but not quite the descriptor for a field?
The simplest way to get the descriptors seems to be to implement methods that derive that information from information available through reflection.
static String getDescriptorForClass(final Class c)
{
if(c.isPrimitive())
{
if(c==byte.class)
return "B";
if(c==char.class)
return "C";
if(c==double.class)
return "D";
if(c==float.class)
return "F";
if(c==int.class)
return "I";
if(c==long.class)
return "J";
if(c==short.class)
return "S";
if(c==boolean.class)
return "Z";
if(c==void.class)
return "V";
throw new RuntimeException("Unrecognized primitive "+c);
}
if(c.isArray()) return c.getName().replace('.', '/');
return ('L'+c.getName()+';').replace('.', '/');
}
static String getMethodDescriptor(Method m)
{
String s="(";
for(final Class c: m.getParameterTypes())
s+=getDescriptorForClass(c);
s+=')';
return s+getDescriptorForClass(m.getReturnType());
}
ASM's Type has getDescriptor and getMethodDescriptor.
String desc = Type.getMethodDescriptor(method);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With