-
- 类的动态加载
- package cn.sxt.demo;
- public class Test2{
// 在编译期间 无论苹果或者橘子是否存在 只要语法格式正确编译器都允许通过 ,只有在程序执行阶段 才会检 //查是否存在该类,如果不存在 ,在报未找到异常 - public static void main(String[] args) throws ClassNotFoundException{
- if("apple".equals(args[0])){
- Class<?> c = Class.forName("cn.sxt.demo.Apple");//全路径名;包名+类名
- System.out.println("创建了苹果类");
- }else if("orange".equals(args[1])){
- Class<?> c = Class.forName("cn.sxt.demo.Orange");
- System.out.println("创建了橘子类");
- }
- }
- }
- 类的静态加载
- 在代码执行期间 无论橘子和苹果是否用的到 编译要求苹果和橘子都必须存在
- public class test1{
- public static void main(args[0])
- {
- if("apple".equals(args[0])){
- Apple apple = new Apple();
- System.out.println("创建了苹果类");
- }
- if("orange".equals(args[0])){
- Orange orange = new Orange();
- System.out.println("创建了橘子类");
- }
- }
- }
反射用途 : 可是使用 assembly 定义加载程序集
使用module获取在模块上定义的所有全局方法
使用constructiorInfo 了解如下的类似信息 构造方法的名称 参数 访问修饰符 和实现详细信息
使用type 的GetConstrutors Getconstrutor方法来调用特定的构造函数
使用MethodInfo 了解如下的类似信息 构造方法的名称 参数 访问修饰符 和实现详细信息
使用type 的GetMethod GetMethods方法来调用特定的构造函数
此外还有 FieldInfo EventInfo PropertyInfo 以及ParameterInfo
优点:
提高了程序的灵活性和扩展性
降低耦合性 提高自适应能力
它允许程序创建和控制任何类的对象 无需提前硬编码目标类
缺点:
性能问题 主要应用在灵活性和拓展性要求很高的系统框架 普通程序不建议使用
便利的同时会带来维护难度的相应提高 反射代码比相应的直接代码更为复杂!
主要使用:
所使用的类java.lang.Class
java.lang.reflect.Construtor; Field;Method;Modifier