说我有两个班级
class parentClass{
String myElement;
}
class childClass extends parentClass{
String notMyElemtent;
}
现在说有一个类childClass的对象。有没有办法以编程方式告诉该对象中的myElement最初属于parentClass?
答案 0 :(得分:5)
你可以用反射来做。使用obj.getClass()。getField(“myElement”)获取表示字段的Field对象。 现在,您可以使用getDeclaringClass()接口的Member方法来获取实际声明此成员的类或接口。所以做这样的事情
childClass obj = new childClass();
Field field = obj.getClass().getField("myElement");
if (field.getDeclaringClass().equals(parentClass.class)) {
// do whatever you need
}
答案 1 :(得分:3)
有没有办法告诉该对象中的myElement最初属于parentClass?
是的,您可以使用reflection来检查超类的字段:
在代码中,这可能看起来像:
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"));
}
输出:
myElement belongs to parentClass: true
notMyElemtent belongs to parentClass: false
答案 2 :(得分:1)
好吧,使用类的getDeclaredField(name)
,如果没有,请尝试查看它的超类等等。适用于多级继承:
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);
答案 3 :(得分:0)
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 {
}