Comparing two classes by its types or class names

前端 未结 7 1100
耶瑟儿~
耶瑟儿~ 2021-02-01 15:34

There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()? Is there any differ

7条回答
  •  面向向阳花
    2021-02-01 15:43

    I ran into a problem comparing two classes using .equals. The above provided solution is not entirely accurate. Class does not implement Comparable.

    Class references are not necessarily true singletons within a JVM because you can have multiple ClassLoaders.

    I was writing a Maven plugin that was digging annotations out of beans after compile. The plugin had one classloader and I had my own classloader. When comparing two classes of the same name from different loaders the comparison would fail.

    The implementation of Object.equals looks like this:

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

    So you will be comparing references.

    If you are comparing classes and you know for sure there will only be one classloader involved you can safely use .equals or c1 == c2 but if you are not sure you should compare by name:

    if(c1.getName().equals(c2.getName()) {
       ...
    }
    

提交回复
热议问题