什么是反射?
The name reflection is used to describe code which is able to inspect other code in the same system (or itself).
反射这个词,用来描述那些能够检查代码的那些代码。
For example, say you have an object of an unknown type in Java, and you would like to call a ‘doSomething’ method on it if one exists. Java’s static typing system isn’t really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called ‘doSomething’ and then call it if you want to.
假设现在你有一个对象,但是你不知道它的类型,然而你却想要调用它的一些方法。原本的java并不能实现这个功能,但是有了反射,你就可以了。
简单来说,反射就是在程序运行的时候(注意是运行的时候!)获得一个类的属性和方法、或者在运行的时候动态创建一个类。
听着是不是还是有点不知所以,那我现在问你,如何编写一个方法来知道一个类里面有多少方法呢?这个普通的代码是无法做到的,但是依靠反射可以很简单完成。
那么反射有什么好处呢?
- 在运行时判断类的一些信息
- 在运行时构造新的类
- 在运行时调用类的方法(甚至是private的)
那么反射有什么坏处呢?