Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get java field and method descriptors at runtime

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?

like image 366
warren Avatar asked Jan 30 '26 12:01

warren


2 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());
}
like image 163
warren Avatar answered Feb 01 '26 03:02

warren


ASM's Type has getDescriptor and getMethodDescriptor.

String desc = Type.getMethodDescriptor(method);
like image 24
Florens Avatar answered Feb 01 '26 03:02

Florens



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!