1

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?

2

3 Answers 3

5

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());
}
0
3

ASM's Type has getDescriptor and getMethodDescriptor.

String desc = Type.getMethodDescriptor(method);
1

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.

3
  • Why not Class.descriptorString() / Class.describeConstable().orElseThrow()? Commented Sep 18, 2021 at 19:54
  • @JohannesKuhn you are right, I changed my answer.
    – Mike Nakis
    Commented Sep 19, 2021 at 11:32
  • 1
    descriptorString() actually comes from java.lang.invoke.TypeDescriptor.OfField - which both java.lang.constant.ClassDesc and java.lang.Class implements. Commented Sep 19, 2021 at 12:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.