从反射中获取字段的类名 [英] Get the Class Name of a Field from reflection
问题描述
我绕圈子走了。
我有一个人类,例如
public class Person {
String name = "";
}
现在,我想反省这个类实例&弄清楚什么类名称声明为。
Now, I would like to introspect this class instance & figure out what Class is name declared as.
所以,name = String或java.lang.String
So, name = String or java.lang.String
这是我的代码:
'this'是Person的实例。
'this' is an instance of Person.
try {
String className = this.getClass().getName();
Class cls = Class.forName(className);
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
int mod = fld.getModifiers();
System.out.println("1. " + fld.toGenericString());
System.out.println("2. " + fld.getName());
System.out.println("3. " + fld.getGenericType() + "]");
Object oj = fld.getType();
// Says that 4: class java.lang.String
System.out.println("4: " + oj.toString());
Class c1 = oj.getClass();
// Should throw Exception
String stype = c1.getDeclaringClass().toString();
System.out.println("5. " + stype);
}
}
catch (Throwable e) {
System.err.println(e);
}
我设法找到了一个声明:
I managed to get to a part that states:
class java.lang.String
class java.lang.String
但我需要它是java.lang.String
but I need it to be "java.lang.String"
任何想法?
推荐答案
尝试.. getType()然后getName()
Try.. getType() and then getName()
fld.getType().getName()
( Aften Green Days'评论) - 请注意
fld.getType()。getCanonicalName()
将给出大多数情况下输出相同。使用内部类时输出不同。以下是来自搜索的链接。根据您对classname的需要,您可以选择getName()或getCanonicalName()
(Aften Green Days' comment) -- Note that
fld.getType().getCanonicalName()
will give same output in most cases. The output is different when innerclasses are used. Here is link came from search. Depending what you need to do with classname you may choose one of getName() or getCanonicalName()
这篇关于从反射中获取字段的类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!