通过类型或类名比较两个类 [英] Comparing two classes by its types or class names

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

问题描述

是否需要根据它们实现的类比较两个对象?什么时候使用getClass()进行比较,什么时候getClass().getName()进行比较? 比较两种Objects类类型(名称)的方法之间有什么区别?

There is need to compare two objects based on class they implement? When to compare using getClass() and when getClass().getName()? Is there any difference between this approaches to compare two Objects class types (names)?

public abstract class Monster { ... }
public class MonsterTypeOne extends Monster { ... }
public class MonsterTypeTwo extends  Monster { ... }

    Monster monster = MonsterTypeOne();
    Monster nextMonster = MonsterTypeTwo();


if(nextMonster.getClass().getName().equals(monster.getClass().getName()) )// #1

if(nextMonster.getClass().equals(monster.getClass()) )// #2

编辑1

那又怎么样:?

nextMonster.getClass().equals(MonsterTypeOne.class)

推荐答案

比较两种Objects类类型(名称)的方法之间是否有区别?

Is there any difference between this approaches to compare two Objects class types (names)?

是的.如果两个类由不同的ClassLoader加载,则它们可能具有相同的名称.

Yes. Two classes may have the same name if they are loaded by different ClassLoaders.

"Java类加载器的基础知识"

最简单的是,类加载器创建由字符串名称引用的类主体的平面名称空间.

At its simplest, a class loader creates a flat name space of class bodies that are referenced by a string name.

> Eclipse –关于两个VM(以及许多类加载器)的故事"

这意味着可以将两个具有相同名称的类同时加载到VM中,前提是它们具有两个单独的ClassLoader

That means it's possible to have two classes with the same name loaded into a VM at once, provided that they have two separate ClassLoaders


何时使用getClass()进行比较以及何时getClass().getName()进行比较?

When to compare using getClass() and when getClass().getName()?

如果您想知道两个对象是否具有相同的类型,则应使用equals方法比较两个类-第一个选项.

If you want to know whether two objects are of the same type you should use the equals method to compare the two classes -- the first option.

我无法想象为什么要这样做,但是如果您想知道两个具有不同具体类型的对象是否具有相同的完全限定名称的类型,则可以使用第二个.如果您不了解Java上下文中的具体类型"和完全限定名称",那么您就不会编写Java的类型分析代码,因此就不想这么做.

I can't imagine why you'd want to do this, but if you want to know whether two objects with different concrete types have types with the same fully qualified name, then you could use the second. If you don't understand "concrete types" and "fully qualified names" in the context of Java then you're not writing type analysis code for java so you don't want to.

这篇关于通过类型或类名比较两个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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