从反射获取字段的类名
我在这件事上兜圈子。
我有一个类 Person,例如
public class Person {
String name = "";
}
现在,我想内省这个类实例 &弄清楚类的名称声明为什么。
所以, name = String 或 java.lang.String
这是我的代码:
“this”是 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);
}
我设法到达这样的部分:
class java.lang.String
但我需要它是“java.lang.String”
有什么想法吗?
Im going round in circles on this.
I have a class Person, eg
public class Person {
String name = "";
}
Now, I would like to introspect this class instance & figure out what Class is name declared as.
So, name = String or java.lang.String
This is my Code:
'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
but I need it to be "java.lang.String"
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试.. getType() 然后 getName()
编辑:(Aften Green Days 的评论) -- 请注意
在大多数情况下,
fld.getType().getCanonicalName()
将给出相同的输出。使用内部类时,输出会有所不同。这是来自搜索的链接。根据您需要对类名执行的操作,您可以选择 getName() 或 getCanonicalName() 之一Try.. getType() and then getName()
Edit:(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()结果是:
results in:
我想我已经解决了,
应该这样做:
I guess I solved it,
Should have done this:
我通过调用它获得了字段的类名
f.getDeclaringClass().getSimpleName()
I got the class name of a field by calling this
f.getDeclaringClass().getSimpleName()