[英]How to find the class which actually holds the element in java
Say I have two classes 说我有两节课
class parentClass{
String myElement;
}
class childClass extends parentClass{
String notMyElemtent;
}
Now say there is an object of class childClass. 现在说有一个子类childClass的对象。 Is there a way programatically tell that myElement in that object belongs to parentClass originally??
有没有办法以编程方式告诉该对象中的myElement最初属于parentClass?
You can do it with reflection. 您可以通过反射来实现。 Use obj.getClass().getField("myElement") to get Field object, representing your field.
使用obj.getClass()。getField(“ myElement”)获取表示您的字段的Field对象。 Now you can use getDeclaringClass() method of Member interface to get class or interface actually declaring this member.
现在,您可以使用Member接口的getDeclaringClass()方法来获取实际声明此成员的类或接口。 So do something like this
所以做这样的事情
childClass obj = new childClass();
Field field = obj.getClass().getField("myElement");
if (field.getDeclaringClass().equals(parentClass.class)) {
// do whatever you need
}
Is there a way to tell that myElement in that object belongs to parentClass originally?
有没有办法告诉该对象中的myElement最初属于parentClass?
Yes, you can use reflection to examine the fields of the super class: 是的,您可以使用反射来检查超类的字段:
In code, this could look like: 在代码中,这可能类似于:
public static boolean belongsToParent(Object o, String fieldName) {
Class<?> sc = o.getClass().getSuperclass();
boolean result = true;
try {
sc.getDeclaredField(fieldName);
} catch (NoSuchFieldException e) {
result = false;
}
return result;
}
public static void main(String[] args) {
childClass cc = new childClass();
System.out.println("myElement belongs to parentClass: " +
belongsToParent(cc, "myElement"));
System.out.println("notMyElemtent belongs to parentClass: " +
belongsToParent(cc, "notMyElemtent"));
}
Output: 输出:
myElement belongs to parentClass: true
notMyElemtent belongs to parentClass: false
Well, use getDeclaredField(name)
of a class, and if its not there, try looking at its super class and so on. 好吧,使用类的
getDeclaredField(name)
,如果不存在,请尝试查看其超类,依此类推。 Works for multiple levels of inheritance: 适用于多个继承级别:
Class<?> clazz = childClass.class;
do {
try {
Field f = clazz.getDeclaredField(fieldName);
//there it is! print the name of the super class that holds the field
System.out.println(clazz.getName());
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
} while (clazz != null);
import java.lang.reflect.Field;
public class Test4 {
public static void main(String[] args){
Child child = new Child();
System.out.println(getDeclaringClass(child.getClass(), "value"));
}
public static String getDeclaringClass(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
} catch (NoSuchFieldException e) {
if(clazz.getSuperclass() != null){
return getDeclaringClass(clazz.getSuperclass(), name);
}else{
return null;
}
}
return clazz.getName();
}
}
class Parent {
String value = "something";
}
class Child extends Parent {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.