@ java反射
理解反射
(反射)是Java被视为动态语言的关键,反射机制允许程序在执行期借助于Reflection API取得任何类的內部信息,并能直接操作任意对象的内部属性及方法
Java反射机制主要提供了以下功能:
在运行时构造任意一个类的对象
在运行时获取任意一个类所具有的成员变量和方法
在运行时调用任意一个对象的方法(属性)
生成动态代理
Class 是一个类; 一个描述类的类.
最常用的方法如下
Method[] methods=ReflectTest.class.getMethods();//获取到public方法
for (Method method:methods){
System.out.println(method.getName());
}
Method[] declaredMethods=ReflectTest.class.getDeclaredMethods();//获取到public方法
for (Method method:declaredMethods){
System.out.println(method.getName());
}
ReflectTest reflectTest = new ReflectTest();
Method methodA = ReflectTest.class.getMethod("setA", int.class);//获取单个public方法
methodA.invoke(reflectTest, 1);//唤醒方法
System.out.println(reflectTest.getA());
Field fieldA = ReflectTest.class.getDeclaredField("a");//获取私有属性
fieldA.set(reflectTest, 2);//给属性赋值
System.out.println(reflectTest.getA());
Method methodAB = ReflectTest.class.getDeclaredMethod("ab");//获取单个方法
String ab;
if (methodAB.getAnnotation(MyAnnotation.class) != null) {//获取方法注解,拦截器中使用
MyAnnotation myAnnotation = methodAB.getAnnotation(MyAnnotation.class);
ab = myAnnotation.getAB();
} else {
ab = (String) methodAB.invoke(reflectTest);
}
System.out.println(ab);
注解代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String getAB() default "";}