1

I am new to reflection and looking to gain hold over the concept.

Please explain the below statement if possible with an example

The Class Object

Before you can do any inspection on a class you need to obtain its java.lang.Class object.

All types in Java including the primitive types (int, long, float etc.) including arrays have an associated Class object.

How does the associated class object of int (primitive) look like?

I am not able to understand the highlighted text.

Link for reference - http://tutorials.jenkov.com/java-reflection/classes.html

Pshemo
  • 122,468
  • 25
  • 185
  • 269
  • int -> Integer , float -> Float , double -> Double ... etc ... I won't downvote ya but they will I reckon ! – Yahya May 03 '17 at 20:26

1 Answers1

2

You can get to them from static methods on the wrapper objects, such as Integer.TYPE. From the Integer.TYPE Javadoc:

The Class instance representing the primitive type int.

Per the JLS 15.8, these are equivalent to the classes of the boxed primitives, so int.class, Integer.class, and Integer.TYPE should be equivalent expressions:

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

...however, as noted in this SO answer, this is inconsistent with the docs for Class.isPrimitive:

These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.

See Also: Boolean.TYPE, Character.TYPE, Byte.TYPE, Short.TYPE, Integer.TYPE, Long.TYPE, Float.TYPE, Double.TYPE, Void.TYPE

This suggests that in earlier versions of the SDK, these objects were not necessarily equivalent.

Community
  • 1
  • 1
Jeff Bowman
  • 90,959
  • 16
  • 217
  • 251
  • 4
    You can also refer to it as `int.class`. – Kevin Krumwiede May 03 '17 at 20:35
  • @KevinKrumwiede See edit. You're right, but the Javadoc is a little bit self-contradictory. – Jeff Bowman May 03 '17 at 20:57
  • Can you please explain what is the use of these class objects? In which scenario they will be useful – Sreemanth Jasti May 03 '17 at 21:10
  • Useful for reflection: method signatures, array of ints. – Joop Eggen May 03 '17 at 21:16
  • I have new question now- Connsider I have a class called Test3. I can get class object using Class myobj=Test3.class. Is this same to creating a new object for the class like Test3 myobj=new Test3();. Are the myobj created same? @JeffBowman – Sreemanth Jasti May 03 '17 at 21:28
  • No, `new Test3()` creates a Test3 instance, and `Test3.class` allows you to access the _Class object_ that Java uses to describe Test3's fields and methods (and so forth). They are very different. (You can use the Class object to create a new Test3 instance, but that is an advanced topic that goes far beyond the limits of this comment box.) – Jeff Bowman May 03 '17 at 21:56