Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

java - What is the use/purpose of primitive type classes?

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

What I don't understand is why these are there. They don't seem to serve any functional role. Using reflection, I searched through the classes, and they have no constructors, no methods, and no fields. For all intents and purposes, they seem empty and useless. The primitive type variables are not even instances of their respective classes, as indicated by the following returning false:

int a = 3;
int.class.isInstance(a);

So why do they exist? They must serve some purpose, maybe for the compiler or something, but whatever it is is completely beyond me. There is even an explicit reference to int.class in the Integer API (and likewise for each primitive type and its respective wrapper Object). I haven't been able to find any reference to their existence, much less their use, in the JLS.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...