2015-08-21 109 views
-1

運行時使用字段和方法描述符來鏈接類。因此,他們應該通過反思獲得。我需要它們在運行時創建Java類。是基於通過像Class.getName()這樣的方法獲得的信息來重建描述符的唯一方法,它幾乎返回一個字段的描述符,但不完全是描述符。在運行時獲取java字段和方法描述符

+0

你是什麼意思的「描述符」?你的意思是除了通過JAVA反射庫提供的信息以外的其他東西嗎? –

+0

https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-4.html#jvms-4.3.2是規範。 – warren

回答

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