检查类类型 (.class) 是否等于其他类类型
以下代码有效吗?
void myMethod (Class classType) {
if (classType == MyClass.class) {
// do something
}
}
myMethod (OtherClass.class);
如果没有,是否有其他方法可以检查传递的 .class (类类型)是否属于类型 - MyClass ?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,如果这两个类是由同一个类加载器加载的,那么该代码是有效的。如果您希望两个类被视为相等,即使它们是由不同类加载器加载的,可能来自不同的位置,基于完全限定名称,那么只需比较完全限定名称即可。
请注意,您的代码仅考虑完全匹配,但是 - 它不会提供
instanceof
在查看值是否引用时所做的那种“赋值兼容性”到作为给定类的实例的对象。为此,您需要查看Class.isAssignableFrom
。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 atClass.isAssignableFrom
.我宁愿比较规范名称以完全确定,classType.getCanonicalName().equals(MyClass.class.getCanonicalName())。
请注意,这可能会带来匿名类和内部类的问题,如果您正在使用它们,您可以考虑使用 getName 代替。
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.
这对我有用:
That worked for me:
我认为您正在寻找
instanceof
。或者你可以比较两个类
I think you are looking for
instanceof
.Alternatively you could compare two classes with
不要使用
classType.getCanonicalName().equals(MyClass.class.getCanonicalName())
以上不会考虑任何泛型(所有地图都相同,所有集合都相同等)
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)