Is there a difference between int.class and (Class<Integer>) Class.getPrimitiveClass("int"); in Java?
1 Answer
Well, first Class doesn't have a getPrimitiveClass(String) method. Second, I found this link which implements a method with that name, from the link
public static final Class<?> getPrimitiveClass(String typeName) { if (typeName.equals("byte")) return byte.class; if (typeName.equals("short")) return short.class; if (typeName.equals("int")) return int.class; if (typeName.equals("long")) return long.class; if (typeName.equals("char")) return char.class; if (typeName.equals("float")) return float.class; if (typeName.equals("double")) return double.class; if (typeName.equals("boolean")) return boolean.class; if (typeName.equals("void")) return void.class; throw new IllegalArgumentException("Not primitive type : " + typeName); }
So, if you're using the method above - the answer is no. They're the same.
3 Comments
Pratik Khadloya
I see it declared in Class.java as a native method.
static native Class getPrimitiveClass(String name);Elliott Frisch
Not public and not in the javadoc. You could maybe use reflection to call it. But it might well blow up in a different version of java.
Lourenco
getPrimitiveClass is declared in java.lang.Class as a native method which visibility is default.
Classdoesn't have publicgetPrimitiveClassmethod. Consider adding library you are using.static native Class getPrimitiveClass(String name);Class.getPrimitiveClassmethod your class MUST be in thejava.langpackage. Not necessarily the JVM java/lang, it could be inside your project.