Comparing Class Types in Java(比较 Java 中的类类型)
问题描述
我想比较一下Java中的类类型.
I want to compare the class type in 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 提供了不同类型的信息.
I wanted to compare in case if the obj passed into the function was extended from MyObject_1 or not. But this doesn't work. It seems like the getClass() method and the .class gives different type of information.
如何比较两个类类型,而不必创建另一个虚拟对象来比较类类型?
How can I compare two class type, without having to create another dummy object just to compare the class type?
推荐答案
试试这个:
MyObject obj = new MyObject();
if(obj instanceof MyObject){System.out.println("true");} //true
由于继承,这对接口也有效:
Because of inheritance this is valid for interfaces, too:
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
For further reading on instanceof: http://mindprod.com/jgloss/instanceof.html
这篇关于比较 Java 中的类类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较 Java 中的类类型


- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 获取数字的最后一位 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01