0

Say I have two classes

class parentClass{
   String myElement;
}
class childClass extends parentClass{
   String notMyElemtent;
}

Now say there is an object of class childClass. Is there a way programatically tell that myElement in that object belongs to parentClass originally??

4

4 回答 4

5

你可以通过反射来做到这一点。使用 obj.getClass().getField("myElement") 获取 Field 对象,代表您的领域。现在您可以使用Member接口的getDeclaringClass()方法来获取实际声明该成员的类或接口。所以做这样的事情

childClass obj = new childClass();
Field field = obj.getClass().getField("myElement");
if (field.getDeclaringClass().equals(parentClass.class)) {
    // do whatever you need
}
于 2013-06-25T09:09:08.287 回答
3

有没有办法告诉该对象中的 myElement 最初属于 parentClass ?

是的,您可以使用反射来检查超类的字段:

在代码中,这可能如下所示:

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
于 2013-06-25T09:03:59.810 回答
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);
于 2013-06-25T09:07:07.613 回答
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 {

}
于 2013-06-25T09:24:59.407 回答