I need to check:
public static boolean check(Class<?> c, Class<?> d)
{
if (/* c inherits from d */)
return true;
else
return false;
}
How can I do that ?
And is that possible without c.newInstance()
?
If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class). For your example, it would be: if(B. class.
The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.
All the classes in Java are inherited from the Object class. It is the parent class in Java. All other classes directly or indirectly inherit the Object class. Inheritance is an object-oriented concept in which one class uses the properties and behavior of another class.
One of the core principles of Object-Oriented Programming – inheritance – enables us to reuse existing code or extend an existing type. Simply put, in Java, a class can inherit another class and multiple interfaces, while an interface can inherit other interfaces.
Use isAssignableFrom
if(d.isAssignableFrom(c)){
// then d is a superclass of c
// in other words, c inherits d
}
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.
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With