Reputation: 2761
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.
Upvotes: 1
Views: 5118
Reputation: 2907
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;
}
Upvotes: 3
Reputation: 370
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.
Upvotes: 0
Reputation: 4532
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.
Upvotes: 6