Frage

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.

War es hilfreich?

Lösung

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

Andere Tipps

There is a method called Class#isInterface() in Class

 if (c.isInterface())
            return true;

Try this out

if(c.isAssignableFrom(d)){
   return true;
} else {
   return false;
}

How about

public boolean isInterface();

According to docs:

Determines if the specified Class object represents an interface type. Returns: true if this object represents an interface; false otherwise.

if (c.isInterface()) return true;

isInterface

public boolean isInterface()

Determines if the specified Class object represents an interface type. Returns: true if this object represents an interface; false otherwise. sAssignableFrom

public boolean isAssignableFrom(Class<?> cls)

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.

Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion. See The Java Language Specification, sections 5.1.1 and 5.1.4 , for details.

Parameters: cls - the Class object to be checked Returns: the boolean value indicating whether objects of the type cls can be assigned to objects of this class Throws: NullPointerException - if the specified Class parameter is null. Since: JDK1.1

have you tried with

c.isInterface()???

from docs

Determines if the specified Class object represents an interface type.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top