4

I accidentally found that this works:

Class<?> a;

a = int.class;
System.out.println(a); // int

a = Integer.class;      
System.out.println(a); // class java.lang.Integer

What does it really mean / do for primitives?

I tried and neither List<int> nor List<int.class> works (yeah, I know I have to use Integer). Also, obviously, I can't invoke getClass() on primitives, so it's useless for type checking of any sort.

In what situation would I use int.class and why is it even present in the language?

1

2 Answers 2

4

You would use it when you are trying to locate a method having an int argument via the reflection API.

1

From the specs:

The type of p.class, where p is the name of a primitive type 
(§4.2), is Class<B>, where B is the type of an expression of 
type p after boxing conversion (§5.1.7).

And

A class literal evaluates to the Class object for the named 
type (or for void) as defined by the defining class loader 
(§12.2) of the class of the current instance.

So how about

Class<Integer> a = int.class;

When to use: Lots of reflection use cases (for instance in argparse4j they use it to map from command line parameters to methods).

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.