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

war*_*ren 1 java reflection

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

war*_*ren 5

获取描述符的最简单方法似乎是实现从通过反射获得的信息中派生该信息的方法。

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());
}
Run Code Online (Sandbox Code Playgroud)