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

时间:2015-08-21 20:32:47

标签: java reflection

运行时使用字段和方法描述符来链接类。因此,它们应该通过反思来获得。我需要它们在运行时创建java类。是否是基于通过Class.getName()等方法获得的信息重建描述符的唯一方法,该方法几乎返回,但不完全返回字段的描述符?

2 个答案:

答案 0 :(得分:1)

获取描述符的最简单方法似乎是实现从反射可用信息中获取信息的方法。

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

答案 1 :(得分:0)

ASM 的 TypegetDescriptorgetMethodDescriptor

String desc = Type.getMethodDescriptor(method);