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

匿名 (未验证) 提交于 2019-12-03 02:54:01

问题:

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 ?

Thanx!

回答1:

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.



回答2:

I'd rather compare the canonical names to be completely sure, classType.getCanonicalName().equals(MyClass.class.getCanonicalName()).

Note that this may bring issues with anonymous and inner classes, if you are using them you may consider using getName instead.



回答3:

That worked for me

public class Test {  void myMethod (Class classType) {     System.out.println(classType.isAssignableFrom(Test.class));    }  public static void main(String[] args) {     Test t = new Test();     t.myMethod( String.class );  }  } 


回答4:

I think you are looking for instanceof.

Animal a = new Tiger(); System.out.println(a instanceof Tiger); // true System.out.println(a instanceof Animal); //true 

Alternatively you could compare two classes with

a.getClass() == b.getClass() 


回答5:

Don't use classType.getCanonicalName().equals(MyClass.class.getCanonicalName()) the above will not consider any generics (all map are the same, all set are the same etc)



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!