Syeda Naqvi
Syeda Naqvi

Reputation: 49

Type field in Boolean Wrapper Class?

In java API documentation, it is written that Boolean wrapper class have 3 fields. True, False and Type.
For Type they have given description that:

TYPE: The Class object representing the primitive type boolean.

I can't understand what is this "type" field for?

Upvotes: 0

Views: 692

Answers (3)

SusanW
SusanW

Reputation: 1615

Every Java class is represented in a running Java program by an object of type java.lang.Class, which, amongst other things, lets you perform reflective operations upon objects of that type. You can normally get to an object's Class by calling obj.getClass(), or by specifying its name explicitly, eg. String.class.

Primitive types, like int and boolean, don't have a class to represent them. But there are situations where it would be appropriate to have a Class object for them, and the TYPE members of the wrapper class types (like java.lang.Integer and java.lang.Double) represent exactly these Class objects.

You might be given one if you perform reflective operations on, say, an array of booleans, like this:

    boolean[] bools = new boolean[1];
    Class<?> c = bools.getClass().getComponentType();
    Assert.assertEquals(Boolean.TYPE, c);  // passes!

Note that the primitive boolean class is NOT the same as the Boolean wrapper class! That is,

    Assert.assertNotSame(Boolean.TYPE, Boolean.class);  // passes!

Upvotes: 1

JB Nizet
JB Nizet

Reputation: 691775

It is used in the reflection API, to represent the type of a boolean argument or return type of a method, or the type of a field of a class.

Upvotes: 0

Mena
Mena

Reputation: 48404

TYPE is a Class<Boolean> compile-time constant of the Boolean wrapper class representing the primitive type (boolean) the Boolean class wraps around.

The same is in all object wrappers: they all have a TYPE constant representing their primitive counterpart (e.g. Integer.TYPE).

Upvotes: 0

Related Questions