gpt4 book ai didi

java - 按类型或类名比较两个类

转载 作者:IT老高 更新时间:2023-10-28 21:11:41 25 4
gpt4 key购买 nike

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

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)

最佳答案

使用class.equals():

if (nextMonster.getClass().equals(monster.getClass()))

或者,因为每个类就像一个单例 - 每个类加载器只有一个类的实例,并且大多数 JVM 只有一个类加载器 - 你甚至可以使用身份比较:

if (nextMonster.getClass() == monster.getClass())

关于java - 按类型或类名比较两个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10465253/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com