当前位置: 代码迷 >> J2EE >> 请教下一个对象怎么获取自己的名字
  详细解决方案

请教下一个对象怎么获取自己的名字

热度:29   发布时间:2016-04-21 22:35:57.0
请问下一个对象如何获取自己的名字?
Person()
{}

Person p1 = new Person();


p1可以调用一个方法,得到p1这个字符串么?也就是它自己的名字。

------解决方案--------------------
如果你定义对象是成员变量,
可以通过:
父类.class.getDeclaredFields()[0].getName()获得你要的名字,
如果是局部变量,我觉得没什么办法。
------解决方案--------------------
刚才试了,如果是多个成员变量,可以这样写:

private static GroupForm abc = new GroupForm();

private static GroupForm bbb = new GroupForm();

private static Tttttt ddd = new Tttttt();

public static void main(String[] args) throws IOException {
//MainTest是定义的地方
Field[] fields = MainTest.class.getDeclaredFields();
if(fields != null && fields.length > 0) {
for(Field f : fields) {
Type t = f.getGenericType();
if(t instanceof Class<?>) {
Class<?> cls = (Class<?>)t; 
//这里GroupForm就是你想要找的类
if(GroupForm.class.isAssignableFrom(cls)){
//输出变量名
System.out.println(f.getName());
}
}
}
}
}
  相关解决方案