2009-06-19 60 views
7

我注意到有一天我可以调用boolean.class,但不是integer.class(或其他原语)。是什么使布尔如此特别?boolean.class?

注:我在谈论boolean.class,而不是Boolean.class(这将有道理)。

Duh:我试过integer.class,而不是int.class。我不觉得愚蠢:\

回答

9

不是integer.class而是int.class。是的你可以。 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()); 
    } 
} 

输出

boolean 
int 
float 
java.lang.Boolean 
6

你可以做int.class。它与Integer.TYPE相同。

int.class.isPrimitive(),boolean.class.isPrimitive()void.class.isPrimitive()等将给出值trueInteger.class.isPrimitive(),Boolean.class.isPrimitive()等,将给出值false

3

那么你可以这样做int.class以及

System.out.println(int.class); 

该关键字的.class用Java 1.1中引入有一个一致的方法来获取类类型和基本数据类型的类对象。

class: Java Glossary

3

布尔并不特殊。您可以拨打电话

int.class 

例如。所有的原始类型都有这个文字。从Sun的Tutorial

最后,还有一个特殊的文字称为类的文字,通过采取类型名称和附加的“.class”形成的;例如,String.class。这是指表示类型本身的对象(类型为Class)。

0

也许愚蠢的延续,但为什么可以分配给boolean.class类<布尔>,虽然哈希码有什么不同?

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()); 
+0

因为`boolean.class`的类型是`Class `。基元不能用作类型参数,因此不存在类“类”。最好不要将问题提交为答案。这应该是它自己的问题,或者是对其他答案之一的评论。 – gdejohn 2011-01-10 12:39:44

相关问题