我有一个类将被传递到一个函数中,它将定义如下:
class ayy{
String blah;
Class a;
Class b;
}
我希望能够调用类 a 和 b 上的 getSimpleName() 方法。目前我正在这样做:
Class c = (Class)argument; // Where argument is the "ayy" class
c.getField("a").getSimpleName();
但这给了我一个错误,说“getSimpleName()”没有为类型字段定义。
最佳答案
您不能直接在反射产生的对象上调用方法,例如您使用 Field
所做的那样,就好像它是所需类型的引用变量一样。
相反,您需要调用 getDeclaredField
,因为getField
only gets public
fields 。此外,您还需要 get()
the value of the Field
,传入 ayy
类的实例,该实例将返回 Field
的值。然后,您需要将其转换为 Class
,因为 get()
返回一个 Object
。然后您可以调用getSimpleName()
。
Class<?> classOfA = (Class<?>) c.getDeclaredField("a").get(anAyy);
String simpleName = classOfA.getSimpleName();
您还需要捕获可能引发的各种与反射相关的异常。
关于java - 检索类型类的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32060703/