Reputation: 1392
this seems to be a newbie question, In Java, how can I check at compile time if someClass.class is derived from a anotherClass.class or at run-time if at compile time is not possible?
Upvotes: 1
Views: 220
Reputation: 40036
Checking in runtime is straightforward as other people has already suggested. However, it is possible to do in compile time with a little trick.
You can make use of generics to have a method like this:
public static <A, B extends A> void isExtends(Class<A> clazzA, Class<B> clazzB) {
// empty
}
If you want to make sure someClass.class is derived from a anotherClass.class, simply put in your code:
isExtends(AnotherClass.class, SomeClass.class);
Compiler will help you to verify if SomeClass extends from AnotherClass.
(But honestly, I wonder if this is actually something useful in real life :P )
Upvotes: 0
Reputation: 310884
You can check at runtime with Class.isAssignableFrom()
if you only have classes, or the instanceof
operator if you have instances.
As for compile time, I don't understand the question. And why wouldn't the person writing the code know before compile time?
Upvotes: 0
Reputation: 424993
In code:
anotherClass.class.isAssignableFrom( someClass.class );
If you want to also check that the other class is a real class (and not an interface) add in a call to isInterface()
:
!anotherClass.class.isInterface() && anotherClass.class.isAssignableFrom( someClass.class );
Example:
System.out.println( Number.class.isAssignableFrom( Integer.class )); // true
Note that instanceof
won't work for you because you don't have instances, only classes.
Excerpt from Javadoc for Class.isAssignableFrom
:
Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.
Upvotes: 3