正常的JAVA编程情况,我们只是对源码进行操作编程。而反射机制的存在,使得我们可以对JAVA字节码进行操作,就是我们编写的JAVA反射源码是对JAVA程序运行时的对象进行操作。
反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为(官网解释-http://docs.oracle.com/javase/tutorial/reflect/index.html:Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. )
用反射与不用反射的一个例子:
package com.ghost.t20140503;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class ReflectionTest {
public static void main(String[] args) {
// 一般做法
MyClass myClass = new MyClass(10);
myClass.increase(5);
System.out.println("正常编程方法得到-> " + myClass.getCount());
try {
// 获取构造方法
Constructor<MyClass> constructor = MyClass.class.getConstructor(int.class);
// 创建对象
MyClass myClassReflect = constructor.newInstance(10);
// 获取方法
Method increaseMethod = MyClass.class.getMethod("increase", int.class);
// 调用increase方法
increaseMethod.invoke(myClassReflect, 5);
Method getCountMethod = MyClass.class.getMethod("getCount");
System.out.println("通过反射得到-> " + (int)getCountMethod.invoke(myClassReflect));
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyClass {
private int count;
public MyClass(int start) {
count = start;
}
public void increase(int step) {
count = count + step;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
一般来说,利用反射编程代码量大,性能也比原始的方法差,代码的可读性也差。那么反射存在的理由是什么呢?其实反射并不只是存在JAVA编程中。
在计算机科学领域,反射是指一类应用,它们能够自描述和自控制。也就是说,这类应用通过采用某种机制来实现对自己行为的描述(self-representation)和监测(examination),并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义。
因此,反射可以让计算机更加智能,让程序可以了解自己,并根据实际情况对自己的结构进行改造。