Java等于Class。 ==与.equals相同

时间:2021-08-19 16:20:00

Can we do a == on a Class variable instead of equals and expect the same result?

我们可以在一个Class变量而不是equals上进行==并期望得到相同的结果吗?

For example:

例如:

Class clazz = xyz;

Case A:

案例A:

if(clazz == Date.class) {
// do something
}

Case B:

案例B:

if(Date.class.equals(clazz)) {
// do something
}

Are Case A and Case B functionally same?

案例A和案例B的功能是否相同?

3 个解决方案

#1


82  

Class is final, so its equals() cannot be overridden. Its equals() method is inherited from Object which reads

类是final,因此不能覆盖equals()。它的equals()方法继承自读取的Object

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

So yes, they are the same thing for a Class, or any type which doesn't override equals(Object)

所以是的,对于Class,或者任何不覆盖equals(Object)的类型,它们都是相同的

To answer your second question, each ClassLoader can only load a class once and will always give you the same Class for a given fully qualified name.

要回答第二个问题,每个ClassLoader只能加载一次类,并且总是为给定的完全限定名称提供相同的Class。

#2


5  

Yes.

是。

Take a look at the Class class description and note that it inherits equals from Object, for which the method reads:

看一下Class类描述并注意它从Object继承equals,该方法读取:

"The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)."

“类Object的equals方法实现了对象上最具辨别力的等价关系;也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一个对象时,此方法才返回true(x = = y的值为true)。“

#3


4  

Yes, since the code for equals(...) for class is the following:

是的,因为类的equals(...)代码如下:

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

#1


82  

Class is final, so its equals() cannot be overridden. Its equals() method is inherited from Object which reads

类是final,因此不能覆盖equals()。它的equals()方法继承自读取的Object

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

So yes, they are the same thing for a Class, or any type which doesn't override equals(Object)

所以是的,对于Class,或者任何不覆盖equals(Object)的类型,它们都是相同的

To answer your second question, each ClassLoader can only load a class once and will always give you the same Class for a given fully qualified name.

要回答第二个问题,每个ClassLoader只能加载一次类,并且总是为给定的完全限定名称提供相同的Class。

#2


5  

Yes.

是。

Take a look at the Class class description and note that it inherits equals from Object, for which the method reads:

看一下Class类描述并注意它从Object继承equals,该方法读取:

"The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true)."

“类Object的equals方法实现了对象上最具辨别力的等价关系;也就是说,对于任何非空引用值x和y,当且仅当x和y引用同一个对象时,此方法才返回true(x = = y的值为true)。“

#3


4  

Yes, since the code for equals(...) for class is the following:

是的,因为类的equals(...)代码如下:

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