简体   繁体   中英

How to get all the interfaces and classes that an object is an instance of?

I have a bunch of proxy objects and I need to identify which classes and interfaces these objects are instance of besides Proxy. In other words, I am not actually looking for the instanceof operator, instead I'm looking to get all classes and interfaces for which instanceof would return true for a particular object.

You can use reflection to determine this. Fundamentally the Java Class class contains accessors which list the interfaces and superclass.

Class clazz = someObject.getClass();
clazz.getInterfaces();
clazz.getSuperclass();

You should read further about the Java Reflection API. A good place might be to start with the Class documentation .

You should use the Class.getInterfaces() and Class.getSuperclass() methods. I believe these will need recursion; an example is:

<T> Set<Class<? super T>> getSuperclasses(Class<? super T> clazz) {
    Set<Class<? super T>> superclasses = new HashSet<>();
    if (clazz.getSuperclass() != null) {
        superclasses.addAll(getSuperclasses(clazz.getSuperclass()));
    }
    return superclasses;
}

And interfaces:

<T> Set<Class<? super T>> getSuperInterfaces(Class<T> clazz) {
    Set<Class<? super T>> superInterfaces = new HashSet<>();
    if (clazz.getInterfaces().length != 0) {
        // Only keep the one you use
        // Java 7:
        for (Class<?> superInterface : clazz.getInterfaces()) {
            // noinspection unchecked
            superInterfaces.add((Class<? super T>) superInterface);
        }
        // Java 8:
        // noinspection unchecked
        Arrays.stream(clazz.getInterfaces()).map(c -> (Class<? super T>) c).forEach(superInterfaces::add);
    }
    return superInterfaces;
}

With Reflection API you can achieve what you want. You would have to scan the packages you want to search for classess the implements or extends a particular interface/class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM