How to identify object types in java [duplicate]

2019-02-06 02:29发布

Possible Duplicate:
How to determine an object's class (in Java)?
Java determine which class an object is

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

4条回答
爷的心禁止访问
2楼-- · 2019-02-06 03:09

You want instanceof:

if (value instanceof Integer)

This will be true even for subclasses, which is usually what you want, and it is also null-safe. If you really need the exact same class, you could do

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

or

if (Integer.class.equals(value.getClass())
查看更多
小情绪 Triste *
3楼-- · 2019-02-06 03:18

Use value instanceof YourClass

查看更多
聊天终结者
4楼-- · 2019-02-06 03:19

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.

查看更多
我命由我不由天
5楼-- · 2019-02-06 03:23

You can compare class tokens to each other, so you could use value.getClass() == Integer.class. However, the simpler and more canonical way is to use instanceof :

    if (value instanceof Integer) {
        System.out.println("This is an Integer");
    } else if(value instanceof String) {
        System.out.println("This is a String");
    } else if(value instanceof Float) {
        System.out.println("This is a Float");
    }

Notes:

  • the only difference between the two is that comparing class tokens detects exact matches only, while instanceof C matches for subclasses of C too. However, in this case all the classes listed are final, so they have no subclasses. Thus instanceof is probably fine here.
  • as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.

    System.out.println("This is a(n) " + value.getClass().getSimpleName());
    
查看更多
登录 后发表回答