java类的比较,在Java中比较类类型

在Java中,对比两个类的类型通常可以使用`instanceof`关键字,而不是直接比较`getClass()`的结果。示例代码展示了如何通过`instanceof`检查对象是否属于某个类或其子类。这种方法适用于类继承和接口实现的情况。
摘要由CSDN通过智能技术生成

I want to compare the class type in Java.

I thought I could do this:

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");

}

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?

解决方案

Try this:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值