What is the use/purpose of primitive type classes?

后端 未结 2 1248
野趣味
野趣味 2020-12-16 00:13

I recently learned that there are Class representations for the primitive types in the JVM. For example, int.class, double.class, and even a

2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-16 00:48

    What I don't understand is why these are there.

    Consider the following:

    public int foo() {
        return 0;
    }
    
    ...
    
    Method method = someClass.getDeclaredMethod("foo");
    Class clazz = method.getReturnType();
    

    Without a Class representation of int, what would the above return? It shouldn't return Integer.class as they're not the same thing. (Imagine trying to distinguish between methods which were overloaded, one with an int and one with an Integer parameter.)

    I've used these classes before to provide default values for arguments when calling them via reflection. Based on the parameter type, I've used null for any reference type, and some (boxed, obviously) primitive value for each of the primitive types.

提交回复
热议问题