我想比较Java中的类类型。
我以为我可以这样做:
class MyObject_1 {}
class MyObject_2 extends MyObject_1 {}
public boolean function(MyObject_1 obj) {
if(obj.getClass() == MyObject_2.class) System.out.println("true");
}
如果传入函数的obj是从MyObject_1扩展的话,我想比较一下。 但这不起作用。似乎getClass()方法和.class提供了不同类型的信息。
如何比较两个类类型,而不必仅仅为了比较类类型而创建另一个虚拟对象?
答案 0 :(得分:44)
试试这个:
MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true
由于继承,这对接口也是有效的:
class Animal {}
class Dog extends Animal {}
Dog obj = new Dog();
Animal animal = new Dog();
if(obj instanceof Animal){System.out.println("true");} //true
if(animal instanceof Animal){System.out.println("true");} //true
if(animal instanceof Dog){System.out.println("true");} //true
有关instanceof:http://mindprod.com/jgloss/instanceof.html
的进一步阅读答案 1 :(得分:28)
如果您不想或不能使用instanceof
,请与equals
进行比较:
if(obj.getClass().equals(MyObject.class)) System.out.println("true");
顺便说一句 - 这很奇怪,因为你的语句中的两个Class
实例应该是相同的,至少在你的示例代码中是这样。如果出现以下情况,可能会有所不同。
答案 2 :(得分:9)
它在我的机器上打印true
。它应该,否则Java中没有任何东西可以按预期工作。 (这在JLS中解释:4.3.4 When Reference Types Are the Same)
您是否有多个类加载器?
啊,并回应此评论:
我意识到我的错字 题。我应该是这样的:
MyImplementedObject obj = new MyImplementedObject ();
if(obj.getClass() == MyObjectInterface.class) System.out.println("true");
MyImplementedObject实现 MyObjectInterface换句话说,我 我正在与它的实施进行比较 对象。
好的,如果你想检查一下你是否可以这样做:
if(MyObjectInterface.class.isAssignableFrom(obj.getClass()))
或更简洁
if(obj instanceof MyobjectInterface)
答案 3 :(得分:3)
如前所述,除非您在两个不同的类加载器上加载相同的类,否则您的代码将起作用。 如果你需要同时在内存中同一个类的多个版本,或者你在飞行编译的东西上做了一些奇怪的事情(就像我一样),这可能会发生。
在这种情况下,如果你想将它们视为同一个类(根据具体情况可能是合理的),你可以匹配它们的名称来比较它们。
public static boolean areClassesQuiteTheSame(Class<?> c1, Class<?> c2) {
// TODO handle nulls maybe?
return c1.getCanonicalName().equals(c2.getCanonicalName());
}
请记住,这种比较将完成它的作用:比较类名;我不认为你能够从一个版本的版本转换到另一个版本,在进行反思之前,你可能想确保你的类加载器混乱的原因。
答案 4 :(得分:1)
检查equals()
的Class.java源代码public boolean equals(Object obj) {
return (this == obj);
}
答案 5 :(得分:0)
嗯......请记住,Class可能会也可能不会实现equals() - 这是规范不需要的。例如,HP Fortify将标记myClass.equals(myOtherClass)。
答案 6 :(得分:0)
已经比较了使用instanceOf
或...将对象与类进行比较。
如果您有两个对象,并且想要将它们的类型与其他对象进行比较,则可以使用:
if (obj1.getClass() == obj2.getClass()) {
// Both have the same type
}
答案 7 :(得分:0)
如果您有两个字符串,并通过对它们调用getClass()方法使用==对其进行了比较,则它将返回true。您得到的是对同一对象的引用。
这是因为它们都是同一类对象的引用。 Java应用程序中的所有类都是如此。 Java只加载一次该类,因此在给定的时间只有给定类的一个实例。
String hello = "Hello";
String world = "world";
if (hello.getClass() == world.getClass()) {
System.out.println("true");
} // prints true