首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2EE开发 >

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

2013-08-20 
请问下一个对象如何获取自己的名字?Person(){}Person p1 new Person()p1可以调用一个方法,得到p1这个字

请问下一个对象如何获取自己的名字?
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());
}
}
}
}
}

热点排行