1

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.

1
  • 4
    Can you share your research into this heavily documented feature? That way we know what knowledge you already have of the subject. Commented Feb 10, 2015 at 17:26

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

1 Comment

getSuperclasses doesn't handle the base case and getSuperInterfaces doesn't recurse.
0

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.

1 Comment

The package scan is for the reverse operation, which was not the OP's question. Package scanning is also a pretty dubious technique because you do not always know all potential sources of packages, the most common being jar files, class files, Internet connections, and bytecode generators.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.