Reflect makes everything impossible.
反射是java 提供的一个利器,同时也是一把双刃剑。
反射可以使我们根据类名来获得类的属性、方法等,即使他是privated的。
写个简单的例子
定义一个Tree类,提供两个private的方法:
public class Tree {
private void absorbSunshine(){
System.out.println("吸收阳光");
}
private void absorbWater(){
System.out.println("吸收水分");
}
}
按照正常的方式调用Tree类的两个方法是行不通的:
public class NormalInvoke {
public static void main(){
Tree tree = new Tree();
Tree.absorbWater();
}
}
提示错误:该方法是not visible的,也就是说我们不能直接调用私有方法。
那么尝试使用反射:
public class InvokeTree {
public static void main(String [] args){
Object c = Tree.class.getClass(); // 通过反射获取Tree
Method[] method = Tree.class.getDeclaredMethods(); //获取Tree类的所有方法
for(Method m : method){
System.out.println(m); //遍历输出Tree类中定义的所有方法
}
}
}
输出结果:
private void duotai.Tree.absorbWater()
private void duotai.Tree.absorbSunshine()
。强大吧
反射技术也是spring框架AOP的核心技术。
来看下反射技术的源码级实现:
Returns the runtime class of this Object. The returned Class object is the object that is locked by static synchronized methods of the represented class.
上面这句话是对getClass方法的解释:返回这个对象的运行时期类。这个返回的class对象是被静态同步方法锁住的。什么鬼
反射是一种技术:
重要的是reflect包中的几个方法:
至于reflect更高深更复杂的用法,鄙人现在还不太熟悉,待续。