aryaxt
aryaxt

Reputation: 77596

Java - Comparing classes?

How can i compare 2 classes?

The following if statement never passes although class is type of MyClass:

public void(Class class) {
   if (class == MyClass.class){

   }
}

Upvotes: 13

Views: 18817

Answers (4)

Mike Samuel
Mike Samuel

Reputation: 120516

To test whether clazz is a (sub) type of MyClass do

MyClass.class.isAssignableFrom(clazz)

From the 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.

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.

So

Object.class.isAssignableFrom(String.class)

is true because each String is also an Object but

String.class.isAssignableFrom(Object.class)

is false because not all Objects are Strings.


The name "isAssignableFrom" comes from the fact that,

Class1 x = (Class2) null;

is only legal when

Class1.class.isAssignableFrom(Class2.class)

I.e., we can assign a field or variable with static type Class1 a value that comes from an expression whose static type is Class2.

Upvotes: 11

Genzer
Genzer

Reputation: 2991

You can use instanceof operator to check if an instance belongs to a specific class or its subclasses.

class MyClass{}

class SubClass extends MyClass{}

public static void main(String args[]) {

    SubClass object = new SubClass();

    if (object instanceof MyClass) {
        System.out.println("It works, too");
    }
}

Upvotes: 6

Matt Ball
Matt Ball

Reputation: 359826

You can use == or .equals() to compare Class objects.

Example:

class MyClass
{
    public static void main (String[] args) throws java.lang.Exception
    {
        MyClass m = new MyClass();
        if (MyClass.class == m.getClass())
        {
            System.out.println("it worked");
        }
    }
}

Demo: http://ideone.com/AwbNT

Upvotes: 7

Carcamano
Carcamano

Reputation: 1173

if (clazz.equals(MyClass.class)) {

}

BTW, class is a reserved word.

Upvotes: 36

Related Questions