1

Is there a difference between int.class and (Class<Integer>) Class.getPrimitiveClass("int"); in Java?

4
  • possible duplicate of What int.class mean Commented Aug 26, 2014 at 20:49
  • 3
    Standard Class doesn't have public getPrimitiveClass method. Consider adding library you are using. Commented Aug 26, 2014 at 20:50
  • 3
    I see it declared in Class.java as a native method. static native Class getPrimitiveClass(String name); Commented Aug 26, 2014 at 22:50
  • Complementing @PratikKhadloya comment, to use Class.getPrimitiveClass method your class MUST be in the java.lang package. Not necessarily the JVM java/lang, it could be inside your project. Commented Aug 19, 2017 at 2:25

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I see it declared in Class.java as a native method. static native Class getPrimitiveClass(String name);
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.
getPrimitiveClass is declared in java.lang.Class as a native method which visibility is default.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.