Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking a class type (.class) is equal to some other class type

Is the following code valid?

void myMethod (Class classType) {    if (classType == MyClass.class) {        // do something    } }  myMethod (OtherClass.class); 

If not is there any other approach where I can check if a passed .class (Class Type) is of type - MyClass ?

like image 664
Fahim Avatar asked Jan 13 '12 12:01

Fahim


People also ask

How do you check if a class is an instance of another class?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

How do you match a class type in Java?

If you had two Strings and compared them using == by calling the getClass() method on them, it would return true. What you get is a reference on the same object. This is because they are both references on the same class object. This is true for all classes in a java application.


1 Answers

Yes, that code is valid - if the two classes have been loaded by the same classloader. If you want the two classes to be treated as equal even if they've been loaded by different classloaders, possibly from different locations, based on the fully-qualified name, then just compare fully-qualified names instead.

Note that your code only considers an exact match, however - it won't provide the sort of "assignment compatibility" that (say) instanceof does when seeing whether a value refers to an object which is an instance of a given class. For that, you'd want to look at Class.isAssignableFrom.

like image 109
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet