Created
March 21, 2013 12:06
-
-
Save madan712/5212559 to your computer and use it in GitHub Desktop.
Java : Function to return type of Object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Date; | |
public class ObjectTypeDetector { | |
public static String getObjectType(Object obj) { | |
String objectType = "null"; | |
if (obj != null) { | |
objectType = obj.getClass().getName(); | |
objectType = objectType.substring(objectType.lastIndexOf(".") + 1); | |
} | |
return objectType; | |
} | |
public static void main(String[] args) { | |
ArrayList<Object> list = new ArrayList<Object>(); | |
list.add(new String("Mike")); | |
list.add(999); | |
list.add(99.0); | |
list.add(new Date()); | |
list.add(true); | |
list.add(new Object()); | |
list.add(null); | |
for (Object obj : list) { | |
System.out.println(obj + " " + getObjectType(obj)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment