Dave
Dave

Reputation: 4060

boolean.class?

I noticed the other day that I can call boolean.class, but not integer.class (or on other primitives). What makes boolean so special?

Note: I'm talking about boolean.class, not Boolean.class (which would make sense).

Duh: I tried integer.class, not int.class. Don't I feel dumb :\

Upvotes: 8

Views: 17028

Answers (5)

bedla.czech
bedla.czech

Reputation: 1219

Maybe dumb continuation, but why is possible to assign boolean.class to Class<Boolean>, although hashCodes are different?

final Class<Boolean> c = boolean.class;     
System.out.println("c := "+c);
System.out.println("boolean.class := "+boolean.class);
System.out.println("Boolean.class := "+Boolean.class);
System.out.println("boolean.class == Boolean.class := "+(boolean.class == Boolean.class));
System.out.println("boolean.class.equals(Boolean.class) := "+boolean.class.equals(Boolean.class));
System.out.println("boolean.class.hashCode := "+boolean.class.hashCode());
System.out.println("Boolean.class.hashCode := "+Boolean.class.hashCode());

Upvotes: 0

glmxndr
glmxndr

Reputation: 46586

Not integer.class but int.class. Yes you can. JRE 6 :

public class TestTypeDotClass{
    public static void main(String[] args) {
        System.out.println(boolean.class.getCanonicalName());
        System.out.println(int.class.getCanonicalName());
        System.out.println(float.class.getCanonicalName());
        System.out.println(Boolean.class.getCanonicalName());
    }
}

outputs

boolean
int
float
java.lang.Boolean

Upvotes: 12

jitter
jitter

Reputation: 54605

Well you can do something like int.class as well

System.out.println(int.class);

The .class keyword was introduced with Java 1.1 to have a consistent way to get the class object for class types and primitive data types.

class: Java Glossary

Upvotes: 3

Bill the Lizard
Bill the Lizard

Reputation: 405775

boolean isn't special. You can call

int.class

for example. All of the primitive types have this literal. From Sun's Tutorial:

Finally, there's also a special kind of literal called a class literal, formed by taking a type name and appending ".class"; for example, String.class. This refers to the object (of type Class) that represents the type itself.

Upvotes: 3

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

You can do int.class. It gives the same as Integer.TYPE.

int.class.isPrimitive(), boolean.class.isPrimitive(), void.class.isPrimitive(), etc., will give a value of true. Integer.class.isPrimitive(), Boolean.class.isPrimitive(), etc., will give a value of false.

Upvotes: 8

Related Questions