比较Class对象 [英] Comparing Class objects

查看:125
本文介绍了比较Class对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将 Class 对象与预定义类列表进行比较。

I have to compare a Class object against a list of pre-defined classes.

是否安全使用 == 还是应该使用等于

Is it safe to use == or should I use equals?

if        (klass == KlassA.class) {
} else if (klass == KlassB.class) {
} else if (klass == KlassC.class) {
} else {
}

注意:我不能使用 instanceof ,我没有对象,我只有 Class object。我(错误)在这种情况下使用它就像一个枚举!

Note: I cannot use instanceof, I don't have an object, I just have the Class object. I (mis)use it like an enum in this situation!

推荐答案

java.lang.Class 不覆盖来自 java.lang.Object 等于方法,其实现如下:

java.lang.Class does not override the equals method from java.lang.Object, which is implemented like this:

public boolean equals(Object obj) {
    return (this == obj);
}

所以 a == b a.equals(b)相同(除非 a 为空)。

So a == b is the same as a.equals(b) (except if a is null).

这篇关于比较Class对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆