简体   繁体   English

如何找到实际上包含Java中元素的类

[英]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.

相关问题 如何找出哪个线程持有显示器? - How to find out which thread holds the monitor? 如何返回持有类java的对象 - How to return the object that holds a class java 找出哪个类/实例持有对打开文件的引用 - Find out which class/instance holds a reference to an open file Java中的main(String [] args)实际上属于哪个类? - To which class the main(String[] args) actually in Java? 如何创建一个包含 class 的任何子级列表的 class? - How to create a class which holds list of any children of a class? (初学者Java)Main方法是指单独的类中的一个保存数组的方法。 第二类的方法将如何设置? - (Beginner Java) Main method refers to a method in a seperate class which holds arrays. How would the method in the second class be set up? 如何在Java中创建一个uuid参数来保存ntp time的值 - how to create a uuid parameter in java which holds the value of ntp time 如何从有效地保存特定参考值的类中查找字段? - How to find a field from a class that holds a specific reference value efficiently? Appium,Java,iOS:如何确定元素是否可见(如果它实际上不在前面) - Appium, Java, iOS: How to find out if element visible, if it's not actually on front 找出实际加载的Java类并减少jar - Find out which Java classes are actually loaded and reduce jar
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM