How to determine object types in java

Possible duplicate:
How to define an object class (in Java)? Java determines which class is an object

I have the following example of an incomplete method for comparing 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, for example

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

This method actually does not work, please help me make it work.

+8
java object class
source share
4 answers

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

Please note that this type of code is usually a sign of poor OO development.

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

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

is false whereas

 "foo" instanceof Object 

truly.

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

+20
source share

You can compare class tokens with each other, so you can use value.getClass() == Integer.class . However, a 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 them is that comparing class tokens only determines exact matches, and instanceof C for subclasses of C However, in this case, all the classes listed are final , so they have no subclasses. So instanceof is probably fine.
  • as stated by JB Nizet, such checks are not an OO design. You can solve this problem in a more OO way, for example.

     System.out.println("This is a(n) " + value.getClass().getSimpleName()); 
+12
source share

Use value instanceof YourClass

+3
source share

Do you want instanceof :

 if (value instanceof Integer) 

This will be true even for the subclasses that you usually want, and it is also unsafe. If you really need the same class, you can do

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

or

 if (Integer.class.equals(value.getClass()) 
+3
source share

All Articles