反射
这个词让我们总想到的是生物里面的反射,所以在编程世界里这个概念虽然很重要,但是很多人没有搞清楚这到底是什么?
官方:https://www.oracle.com/java/technologies/javareflection.html
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or “introspect” upon itself, and manipulate internal properties of the program. For example, it’s possible for a Java class to obtain the names of all its members and display them.
翻译:
反射是Java编程语言的一个特性,它允许正在执行的Java程序检查或“内省”自身,并操作程序的内部属性。例如,Java类可以获取其所有成员的名称并显示它们。
我的理解:反射 就是可以获取反映类的变量,或者方法,可以修改变量或者使用方法
这个解释反射有意思:
反射定义(有意思)
2.1.2 Reflection反射
代码
package com.reflection.mark;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionTest {
//只会获得public的成员变量
public int aVar;
protected int bVar;
int cVar;
private int dVar;
//只会获得public的方法
public void doSomething1() {
System.out.println("doSomething1 invoked");
}
void doSomething2() {
System.out.println("doSomething2 invoked");
}
public static void main(String[] args) {
Field[] fields = (ReflectionTest.class).getFields();
for (Field f : fields) {
System.out.println("ReflectionTest class have member is :" + f.getName());
}
Method[] methods = (ReflectionTest.class).getMethods();
for (Method m : methods) {
//如果不加条件,就会报 wrong number of arguments错误 也获取了main方法 参数不匹配
if (m.getName().equals("doSomething1") || m.getName().equals("doSomething2")) {
try {
//执行方法
m.invoke(new ReflectionTest());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
}
}
执行结果:
流程:
获得class ->调用getFields() 或者getMethods() 获取public 修饰的方法或者成员变量
设计类
java.lang.Class
Class类里面import
java.lang.reflect.* 这个包下的很多类 是类的定义 成员变量 方法
Class类反射相关的方法
Modifier and Type | Method and Description |
---|---|
Field[] | getFields() 返回包含一个数组 Field对象反射由此表示的类或接口的所有可访问的公共字段 类对象。 |
Method[] | getDeclaredMethods() 返回包含一个数组 方法对象反射的类或接口的所有声明的方法,通过此表示 类对象,包括公共,保护,默认(包)访问和私有方法,但不包括继承的方法。 |
访问修改私有成员变量
package com.reflection.mark;
import java.lang.reflect.Field;
public class ReflectionTestByPrivateUse {
private int dVar = 1;
public static void main(String[] args) {
Field field = null;
try {
//用getDeclaredField方法获取指定私有成员变量
field = (ReflectionTestByPrivateUse.class).getDeclaredField("dVar");
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
/*setAccessible 方法出处
Class AccessibleObject public void setAccessible(boolean flag)
原因参见:
https://blog.csdn.net/gao_zhennan/article/details/123828322
*/
field.setAccessible(true);
ReflectionTestByPrivateUse reflectionTestByPrivateUse = new ReflectionTestByPrivateUse();
int value = 0;
try {
//设置某个对象的field的值
field.set(reflectionTestByPrivateUse, 8);
value = (int) field.get(reflectionTestByPrivateUse);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
System.out.println(value);
}
}
反射操作注解
总之,反射在Java里面有很大的作用,包括对Spring的发明在底层也起到了关键作用。理解好反射,夯实基础,很重要