反射
Java.Reflection
跟框架衔接
1、概念
反射机制允许程序在执行期借助于Reflection API取得任何类的内部信息,并能直接操作任意对象的内部属性及方法
Java反射优缺点
优点:
可以实现动态创建对象和编译,体现出很大的灵活性
缺点:
对性能有影响。反射基本上是解释操作,我们可以告诉JVM,我们希望做什么并且它满足我们的要求。这类操作总慢于直接执行相同的操作。
package com.hao.ex1;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class Apple {
private int price;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public static void main(String[] args) throws Exception {
//正常调用
Apple apple = new Apple();
apple.setPrice(5);
System.out.println("Apple Price:"+apple.getPrice());
//反射调用
//1、获取类的 Class 对象实例c1
Class c1 = Class.forName("com.hao.ex1.Apple");
//获取方法的 Method 对象
Method setPriceMethod = c1.getMethod("setPrice", int.class);
//2、根据 Class 对象实例获取 Constructor 对象
Constructor appleConstructor = c1.getConstructor();
//3、使用 Constructor 对象的 newInstance 方法获取反射类对象
Object appleObj = appleConstructor.newInstance();
//利用invoke方法调用方法
setPriceMethod.invoke(appleObj,14);
Method getPriceMethod = c1.getMethod("getPrice");
System.out.println("Apple Price:"+getPriceMethod.invoke(appleObj));
}
}
运行结果: