说明
类的声明包括常见的修饰符:public 、protected、private、abstract、static、final、strictfp等、类的名称、类的泛型参数、类的继承类、类的注解等信息。
知识点
Class类 实例表示正在运行的Java应用程序中的应用和接口。
枚举是一种类,注释是一种接口。
数组被映射为Class对象的一个类,具有相同元素类型和维度的数组共享该Class对象。
基本的Java类型和关键字void也表示为Class对象,没有公共构造方法。Class对象是在加载类时由Java虚拟机及通过调用类加载器中的defineClass方法自动构造的。
Class类常用的方法
方法名 | 说明 |
---|---|
forName(String className) | 根据给定的名称获取Class对象 |
getAnnotations() | 返回此Class对象上存在的注释 |
getCanonicalName() | 返回Java Language Sepecification中定义的底层类的规范化名称 |
getGenericInterfaces() | 返回泛型形式的对象类所实现的接口 |
getGenericSuperclass() | 返回泛型形式的对象所直接继承的超类 |
getModifiers() | 返回此类或接口以整数编码的Java语言修饰符 |
getTypeParameters() | 按声明顺序返回TypeVariable对象的一个数组 |
实例代码
package reflect;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
public class ClassDeclarationViewer {
public static void main(String[] args) throws ClassNotFoundException {
Class<?> clazz = Class.forName("java.util.ArrayList"); //获得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(typeVariable + "\t");
}
}else {
System.out.println("空");
}
//输出类实现的所有接口
Type[] interfaces = clazz.getGenericInterfaces();
System.out.println("类所实现的接口:");
if (interfaces.length != 0) {
for (Type type:interfaces) {
System.out.println(type + "\t");
}
}else {
System.out.println("空");
}
//输出类的直接继承类
Type superClass = clazz.getGenericSuperclass();
System.out.println("类的直接继承类为:");
if (superClass != null) {
System.out.println(superClass );
}else {
System.out.println("空");
}
//输出类的所有注释信息,有些注信息是不能用反射获得的
Annotation[] annotations = clazz.getAnnotations();
System.out.println("类的注释:");
if (annotations.length != 0 ) {
for (Annotation annotation: annotations
) {
System.out.println("\t" + annotation);
}
}else{
System.out.println("空");
}
}
}
运行结果
类的标准名:java.util.ArrayList
类的修饰符为:public
类的泛型参数:
E
类所实现的接口:
java.util.List<E>
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
类的直接继承类为:
java.util.AbstractList<E>
类的注释:
空
Process finished with exit code 0
反射提供了一种用来获取类的信息方式。