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?
3 Answers
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);
Instead of creating and passing around strings, it is much better to use the interfaces found in the java.lang.constant
package for this purpose.
See ClassDesc
, ConstantDescs
, MethodTypeDesc
, etc.
These interfaces contain static factory methods that instantiate package-private classes that do the work.
java.lang.Class
has a describeConstable()
method which you can use as a starting point.
-
Why not
Class.descriptorString()
/Class.describeConstable().orElseThrow()
? Commented Sep 18, 2021 at 19:54 -
-
1
descriptorString()
actually comes fromjava.lang.invoke.TypeDescriptor.OfField
- which bothjava.lang.constant.ClassDesc
andjava.lang.Class
implements. Commented Sep 19, 2021 at 12:19