What is the use/purpose of primitive type classes?

♀尐吖头ヾ 提交于 2019-11-29 01:49:49

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.

It is a cheap ass solution that turns out badly.

Before 1.5, Java types can be categorized as

java type
    primitive type
    reference type
        class type (including interface)
        array type

Then ideally, java reflection should provide 5 concepts mirroring these 5 types. But they used a single Class to represent them all, including primitive and array types. So a Class does not necessarily mean a class.

That's still manageable. But after 1.5, Java types become more complicated, so a new Type is introduced. Unfortunately, instead of having a new and clean hierarchy that directly mirror language spec, they decides to make Class a subtype of Type; not only the old mess is brought in, it spawns some new mess, and the whole Type hierarchy is unintelligible.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!