一尘不染

什么是类描述符?

java

什么是类描述符?

它是Class特定类的对象吗?


阅读 215

收藏
2020-12-03

共1个答案

一尘不染

是的,Class对象是某个“类”的类描述符。

API中

此类的实例表示正在运行的Java应用程序中的类和接口。枚举是一种类,注释是一种接口。每个数组还属于一个反映为Class对象的类,该类对象由元素类型和维数相同的所有数组共享。原始Java类型(布尔型,字节型,字符型,短型,整型,长型,浮点型和双精度型)以及关键字void也都表示为Class对象。

这是一个简单使用Class方法来示例性地描述类型的示例:

static void describe(Class<?> clazz, String pad, String leadin) {
    if (clazz == null) return;
    String type =
        clazz.isInterface() ? "interface" :
        clazz.isArray() ? "array" :
        clazz.isPrimitive() ? "primitive" :
        clazz.isEnum() ? "enum" :
        "class";
    System.out.printf("%s%s%s %s ( %s )%n",
        pad, leadin, type, clazz.getSimpleName(), clazz.getName());
    for (Class<?> interfaze : clazz.getInterfaces()) {
        describe(interfaze, pad + "   ", "implements ");
    }
    describe(clazz.getComponentType(), pad + "   ", "elements are ");
    describe(clazz.getSuperclass(), pad + "   ", "extends ");
}
static void describe(Class<?> clazz) {
    describe(clazz, "", "");
    System.out.println();
}
public static void main(String[] args) {
    describe(boolean[][].class);
    describe(java.math.RoundingMode.class);
    describe(java.util.ArrayList.class);
    describe(void.class);
}

上面的代码片段产生以下输出:

array boolean[][] ( [[Z )
   implements interface Cloneable ( java.lang.Cloneable )
   implements interface Serializable ( java.io.Serializable )
   elements are array boolean[] ( [Z )
      implements interface Cloneable ( java.lang.Cloneable )
      implements interface Serializable ( java.io.Serializable )
      elements are primitive boolean ( boolean )
      extends class Object ( java.lang.Object )
   extends class Object ( java.lang.Object )

enum RoundingMode ( java.math.RoundingMode )
   extends class Enum ( java.lang.Enum )
      implements interface Comparable ( java.lang.Comparable )
      implements interface Serializable ( java.io.Serializable )
      extends class Object ( java.lang.Object )

class ArrayList ( java.util.ArrayList )
   implements interface List ( java.util.List )
      implements interface Collection ( java.util.Collection )
         implements interface Iterable ( java.lang.Iterable )
   implements interface RandomAccess ( java.util.RandomAccess )
   implements interface Cloneable ( java.lang.Cloneable )
   implements interface Serializable ( java.io.Serializable )
   extends class AbstractList ( java.util.AbstractList )
      implements interface List ( java.util.List )
         implements interface Collection ( java.util.Collection )
            implements interface Iterable ( java.lang.Iterable )
      extends class AbstractCollection ( java.util.AbstractCollection )
         implements interface Collection ( java.util.Collection )
            implements interface Iterable ( java.lang.Iterable )
         extends class Object ( java.lang.Object )

primitive void ( void )

API链接

参考文献

2020-12-03