Java - Comparing classes?

18,089

Solution 1

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

}

BTW, class is a reserved word.

Solution 2

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.

Solution 3

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

Solution 4

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");
    }
}
Share:
18,089

Related videos on Youtube

aryaxt
Author by

aryaxt

Updated on January 10, 2020

Comments

  • aryaxt
    aryaxt over 4 years

    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){
    
       }
    }
    
    • Cristian
      Cristian almost 13 years
      I doubt it compiles at all... on the other hand if it's just pseudocode, then I don't see anything weird. Can you paste the actual code?
  • Soup
    Soup over 11 years
    klass is also a common var name.
  • Mike Samuel
    Mike Samuel over 10 years
    final Class<E> SAN_DIEGO

Related