Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How Can I Check If A Class Is Inheriting From Some Class Or Interface?

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() ?


The title was wrong at the first time. Now it's correct.
like image 769
Bitterblue Avatar asked Apr 25 '13 08:04

Bitterblue


People also ask

How do you know if a class inherits from another Java?

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.

Is there a way to check if a class is a subclass of another class Java?

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.

Are classes in Java inherited from which class?

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.

Can a class inherit from a class and an interface Java?

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.


1 Answers

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

like image 143
Kevin Bowersox Avatar answered Nov 04 '22 05:11

Kevin Bowersox