反射
Reflection框架的灵魂,可以动态的创建和使用对象
反射是解释执行,速度会变慢
new和newInstance的区别:
使用newInstance有两个前提:
1.这个类已经加载;
2.这个类已经连接了。
newInstance()实际上是把new这个方式分解为两步,即首先调用Class加载方法加载某个类,然后实例化。这种分步的方式有利于解耦。
newInstance: 弱类型。低效率。只能调用无参构造。
new: 强类型。相对高效。能调用任何public构造。
public class Exe {
public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\re.properties"));
String classfullpath = properties.get("classfullpath").toString();
String method = properties.get("method").toString();
Class cls = Class.forName(classfullpath);
//获取已加载的类的对象实例
Object o = cls.newInstance();
//通过方法名method,获得一个对应的方法对象
Method method1 = cls.getMethod(method);
//然后通过方法对象,调用方法
method1.invoke(o);//传统形式:对象.方法() 反射中形式:方法.invoke(对象)
}
}
ocp原则:开闭原则
在不改变源码的情况下,来扩展功能
getClass获取的是运行类型
Java程序在计算机的三个阶段:
-
代码\编译阶段
-
Class类加载阶段
-
Runtime运行阶段
哪些类型有Class对象?
各种类
interface
数组
enum
annotation注解
基本数据类型
void
静态加载:编译时加载相关的类
动态加载:运行时加载需要的类,降低了依赖性
invoke(o,"实参");//如果是静态方法,这个对象o可以写成null