/**
*类的声明包括常见修饰符(public、protected、private、abstract、statc、final等)、
* 类的名称、类的泛型参数、类的集成类(实现的接口)和类的注解等
* Class类的实例表示正在运行的Java应用程序中的类和接口。
* 枚举是一种类,注解是一种接口
* 每个数组属于被映射为Class对象的一个类,所有具有相同元素类型和维数的数组都共享该Class对象。
* Java的基本类型和关键字void也表示为Class对象,但没有构造方法
* Class对象是在加载类时由Java虚拟机以及通过调用类加载器中的defineClass()方法自动构造的
*/
public class ClassDeclarationViewer {
public static void main(String[] args) throws ClassNotFoundException{
Class<?> clazz = Class.forName("java.util.ArrayList");
System.out.println("类的标准名称:"+clazz.getCanonicalName());
System.out.println("类的修饰符:"+Modifier.toString(clazz.getModifiers()));
//输出类的泛型参数
TypeVariable<?>[] typeVariables = clazz.getTypeParameters();
System.out.println("类的泛型参数:");
if (typeVariables.length!=0) {
for (TypeVariable<?> typeVariable : typeVariables) {
System.out.println("\t"+typeVariable);
}
}else {
System.err.println("\t空");
}
//输出类所实现的所有接口
Type[] interfaces = clazz.getGenericInterfaces();
System.out.println("类所实现的接口:");
if (interfaces.length!=0) {
for (Type type : interfaces) {
System.out.println("\t"+type);
}
}else {
System.err.println("\t空");
}
//输出类的直接继承类,如果是继承自Object则返回空
Type superClass = clazz.getGenericSuperclass();
System.out.println("类的直接继承类:");
if (superClass!=null) {
System.out.println("\t"+superClass);
}else {
System.err.println("\t空");
}
//输出类的所有注解信息,有些注解信息是不能用反射获得的
Annotation[] annotations = clazz.getAnnotations();
System.out.println("类的注解");
if (annotations.length!=0) {
for (Annotation annotation : annotations) {
System.out.println("\t"+annotation);
}
}else {
System.err.println("\t空");
}
}
}
输出结果如下:
转载于:https://blog.51cto.com/mazongfei/1908118