Java反射 获取Class及Class对应信息

一.获取Class的三种方式

  1. Class.forName(String clazzName) 必须指定全限定类名(com.xxx.xxx.Xxx) 

  2. 调用某个类的class属性获取Class对象  Object.class

  3. 调用某个对象的getClass()方法  obj.getClass()

二.从Class中获取信息

1.获取构造器(Constructor)
getConstructor(Class<?>...parameterTypes)返回 public 指定形参的 Constructor
getConstructors()  返回 public 所有的Constructor
getDeclaredConstructor(Class<?>...parameterTypes) 返回 任何访问权限 指定形参的 Constructor
getDeclaredConstructors();  返回 所有 任何访问权限的Constructor

2.获取方法(Method)
getMethod(String name,Class<?>...parameterTypes) 返回 public 指定名字、形参的 Method
getMethods() 返回 public 所有Method
getDeclaredMethod(String name,Class<?>...parameterTypes) 返回 任何访问权限 指定名字、形参Method
getDeclaredMethods(); 返回 任何访问权限 所有Method

3.获取成员变量(Field)
getField(String name)  返回 public 指定名字的 Field
getFields()  返回 public 所有Field
getDeclareField(String name)  返回 任何访问权限 指定名字 Field
getDeclareFields()  返回 任何访问权限 所有 Field

4.获取Class上的注解(Annotation)
getAnnotation(Class<A> annotationClass) 获取修饰该Class类的 指定类型的 Annotation
getDeclaredAnnotation(Class<A> annotationClass) 获取 修饰该Class类的、指定类型的Annotation   /... jdk1.8新增.../
getAnnotations()   返回该修饰该Class类的所有Annotation
getDeclaredAnnotations() 返回 修饰该Class类的 所有Annotation

5.获取Class相关的内部类、外部类、接口类、父类
getDeclaredClasses()   返回该Class类中 所有 内部类
getDeclaringClass()  返回该Class类中 所在的 外部类(如果该类是个内部类的话)
getInterfaces()     返回该Class类 所有的 已实现的接口
getSuperclass()    返回该Class类的 父类

6.其他信息
Package getPackage() 获取此类的包
String getName 返回该类的名称 (全限定名 : com.xxx.xxx.Xxx)
String getSimpleName()返回该类的简称  (单类名 : Xxx)

7.判断方法 (返回boolean)
  isAnnotation()  该类是否为注解类型 (@interface定义)
  isAnnotationPresent(Class<? extends Annotation> annotationClass) 该类中是否使用过(某个指定)注解
  isAnonymousClass()  该类是否是一个匿名类
  isEnum() 该类是否是一个枚举类
  isInterface() 该类是否是一个接口

猜你喜欢

转载自blog.csdn.net/u012309392/article/details/83476343