您的位置:首页 > 其它

反射reflection

2011-04-26 17:29 218 查看
反射的定义

在计算机领域中的反射和光学上的反射在概念上有类似之处。正是因为光在镜面发生了反射,人们才能在镜子中看到自己。而计算机领域的反射也是如此--因为有了反射,程序可以在运行时,通过反射看到自己,审视自己。不同的是人们不能改变自己在镜子中的摸样,而计算机程序不仅可以看到自己,还能改变自身的行为。

下面是两种反射的定义:
1, A program that can analyze the capabilities of classes is called reflective.

2, 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.

总结一下反射典型的用途是

1,Extensibility Features 比如我们在代码中使用log4j这种第三方工具,调用了它的一个方法。而引用的jar包中都是class文件(字节码),那么怎么才能知道引用的是否正确呢?这里必须使用反射。

2,Class Browsers and Visual Development Environments 指IDE中需要使用反射的地方。例如没有反射,我们就不能在IDE中方便的浏览所引用的class的内容。

3,Debuggers and Test Tools 这里特别提到了代码覆盖率的问题:

Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to insure a high level of code coverage in a test suite.

指一些测试工具利用反射确定测试用例的代码覆盖率问题。

然后是反射的缺点

1,性能差

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.

2,安全问题

3, Since reflection allows code to perform operations that would be illegal in non-reflective code 所以暴露class内部+不当使用可能会导致一些问题。

如何使用反射

其实使用反射很简单~~就是调用relection 提供的APIs~

For every type of object, the Java virtual machine instantiates an immutable instance of

java.lang.Class

which provides methods to examine the runtime properties of the object including its members and type information.

这个
java.lang.Class
实际指一个名叫class的类,不是平时说的广义上的类。

例如java.lang.class类中的getClass()方法可以返回一个Class的实例:

Employee e;
Class cl = e.getClass();


反射是如何实现的

由上面的例子我们可以知道,在java程序运行时JVM中存储了类的内部信息,而程序代码可以访问这些信息。例如上例,假如代码使用了Spring,对象e的类型是在运行时决定的,那么e.getClass()就是从JVM中得到e的真实类型,而不是从代码的语义上分析出来的。

除了runtime,在编写代码时,反射也会起作用。例如前面提到的IDE的功能,java程序就不在运行中。

reflection的概念已经清楚了。剩下的内容可以分为三个方面:

1,Using Reflection to Analyze the Capabilities of Classes

2,Using Reflection to Analyze Objects at Runtime

(1,2都包括取得类的构造函数,成员变量,成员方法,Modifier 修饰符的方法。)

3,其他一些reflection的应用包括array,proxy和reflection permission。

具体去看java.lang.reflect package。这东西等以后具体要用的时候再研究~~~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: