Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to identify object types in java [duplicate]

Tags:

java

object

class

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

The method can be called as:

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

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

like image 711
Harsha Avatar asked May 10 '12 09:05

Harsha


1 Answers

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.

like image 50
JB Nizet Avatar answered Sep 28 '22 08:09

JB Nizet