类加载
基本说明
反射机制是Java实现动态语言的关键,也就是通过反射实现类动态加载
- 静态加载:编译时加载相关的类,如果没有则报错,依赖性太强
- 动态加载:运行时加载需要的类,如果运行时不用该类,则不报错,降低了依赖性
- 静态加载例子:
Scanner scanner = new Scanner(System.in);
String key = scanner.next();
switch(key){
case "1":
Dog dog = new Dog();
dog.method();
break;
case "2":
break;
}
代码虽然不一定会用到Dog类,但是会静态记载,报错找不到类"Dog"
- 动态加载例子:
Scanner scanner = new Scanner(System.in);
String key = scanner.next();
switch(key){
case "1":
Dog dog = new Dog();
dog.method();
break;
case "2":
Class cls = Class.forName("Person");//加载Person类,但是编译的时候不会加载
Object o = cls.newInstance();
Method m = cls.getMethod("method_");
m.invoke(o);
break;
}
标签:case,2025.1,scanner,Dog,key,new,20,JavaSE,加载
From: https://www.cnblogs.com/luvisdru9/p/18682682