简体   繁体   English

在运行时获取 java 字段和方法描述符

[英]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.我需要它们来在运行时创建 Java 类。 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?是基于通过 Class.getName() 等方法获得的信息重建描述符的唯一方法,该方法返回几乎但不完全是字段的描述符?

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 的TypegetDescriptorgetMethodDescriptor

String desc = Type.getMethodDescriptor(method);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM