如何在java中识别对象类型 [英] How to identify object types in java

查看:510
本文介绍了如何在java中识别对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

如何确定对象的类(用Java)?

Java确定一个对象是哪个类

我有以下样本不完整的方法来比较给定对象的对象类型

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

}

我们可以将此方法称为

test("Test");
test(12);
test(10.5f);

此方法实际上无法正常工作,请帮助我使其正常工作

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

推荐答案

你忘了 .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");
}

请注意,这种代码通常是OO设计不佳的标志。

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

另请注意,将对象的类与类进行比较并使用instanceof不是一回事。例如:

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

为假,而

"foo" instanceof Object

为真。

是否一个或者必须使用另一个取决于您的要求。

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

这篇关于如何在java中识别对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆