Question

How can I check is Primitive Data Type of given parameter ?

public static void main(String[] args) {
    if (isPrimitive("test")) {
        System.out.println("True");
    }
    if (isPrimitive(1)) {
        System.out.println("True");
    }
}

public static boolean isPrimitive(Object o) {
    // Here what would I do ?
}
Was it helpful?

Solution

When you call isPrimitive(1) , an auto-boxing will be performed. It means isPrimitive(Object o) gets an Integer, NOT int. In this method it's impossible to know if the argument is an primitive data type. What's more, Java is an static language, so the developer should know its data type

Ref: Java7 Auto Boxing

OTHER TIPS

You could make some overloaded methods that accept different types of parameters. You could make some that accept only primitive wrappers, one that accepts a String and one that accepts an Object. For the one that accepts a String you could use different types of primitive wrapper classes to test if the parseXXX() method works correctly. The method that accepts an Object as a parameter would return always false since the overloaded methods should cover all the primitive types.

You cannot know that by the method with parameter Object o, since if you passed an int, char, boolean they would be autoboxed to the wrapper class, in the method you would never know it is autoboxed primitive or the wrapper classes (Integer, Long, Boolean...)

Primitive data type don't extends Object so you can't call this method with parameter 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top