Java - Comparing classes?
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 Object
s are String
s.
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");
}
}
Related videos on Youtube
aryaxt
Updated on January 10, 2020Comments
-
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 almost 13 yearsI 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 over 11 years
klass
is also a common var name. -
Mike Samuel over 10 years
final Class<E> SAN_DIEGO