Search code examples
javaclasstypesprimitive

Primitive classes in Java


What is the use of classes like int.class or double.class

For example you can not do something like

    Object val=getValue();
    if(val instanceof int){

    }

or

int i = new int();

Yes I know it is not possible because int is not Object type. However, what is the need to have those primitive classes? I do not see any clear explanation of this in Oracle documentation.


Solution

  • It can be useful for reflection.

    For example if you wanted to use Class.getDeclaredMethod to lookup a method that took an int as a parameter, you might do something like:

    //Find the method foo(int)
    Method theMethod = theClass.getDeclaredMethod("foo", int.class);