java 对象识别,如何在java中识别对象类型

该博客指出一个不工作的Java方法,用于比较对象的类型。作者提醒读者使用`.class`而不是`==`来检查对象类型,并警告这种代码可能表示不良的面向对象设计。此外,还解释了`getClass()`与`instanceof`的区别。解决方案是修正条件语句,添加`.class`关键字。
摘要由CSDN通过智能技术生成

I have following sample incomplete method to compare the object type of a given object

public void test(Object value) {

if (value.getClass() == Integer) {

System.out.println("This is an Integer");

}else if(value.getClass() == String){

System.out.println("This is a String");

}else if(value.getClass() == Float){

System.out.println("This is a Fload");

}

}

we can call this method like

test("Test");

test(12);

test(10.5f);

this method is not actually working, please help me to make it work

解决方案

You forgot the .class:

if (value.getClass() == Integer.class) {

System.out.println("This is an Integer");

}

else if (value.getClass() == String.class) {

System.out.println("This is a String");

}

else if (value.getClass() == Float.class) {

System.out.println("This is a Float");

}

Note that this kind of code is usually the sign of a poor OO design.

Also note that comparing the class of an object with a class and using instanceof is not the same thing. For example:

"foo".getClass() == Object.class

is false, whereas

"foo" instanceof Object

is true.

Whether one or the other must be used depends on your requirements.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值