Java反射之静态加载和动态加载的简单实例

时间:2022-09-23 14:41:19

静态加载:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package com.imooc.加载类;
 
public class Office_Static {
    public static void main(String[] args) {
        //new 创建对象,是静态加载类,在编译时刻就需要加载所有的可能使用到的类
        if("Word".equals(args[0])){
            Word w = new Word();
            w.start();
        }
        if("Excel".equals(args[0])){
            Excel e = new Excel();
            e.start();
        }
    }
}

这个程序编译时必须有Word和Excel这两个类存在才行,即使判断后用不到Excel也要加载

动态加载

1、接口OfficeAble :

?
1
2
3
4
5
package com.imooc.加载类;
 
public interface OfficeAble {
    public void start();
}

2、Word实现接口:

?
1
2
3
4
5
6
7
8
package com.imooc.加载类;
 
public class Word implements OfficeAble{
    public void start(){
        System.out.println("word start");
    }
 
}

3、Excel实现接口:

?
1
2
3
4
5
6
7
8
package com.imooc.加载类;
 
public class Excel implements OfficeAble{
 
    public void start(){
        System.out.println("excel start");
    }
}

4、Main方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package com.imooc.加载类;
 
public class OfficeBetter {
    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            //动态加载类,在运行时刻加载
            Class c = Class.forName(args[0]);//在运行配置里面输入com.imooc.加载类.Excel
            //通过类类型,创建该类对象(先转换为Word和Excel的共同接口OfficeAble)
            OfficeAble oa = (OfficeAble)c.newInstance();
            oa.start();
            
            //不推荐下面两种,因为不确定是加载Word还是Excel,要强转
//          Word word = (Word)c.newInstance();
//          word.start();
//          Excel excel = (Excel)c.newInstance();
//          excel.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}

以上就是小编为大家带来的Java反射之静态加载和动态加载的简单实例的全部内容了,希望对大家有所帮助,多多支持服务器之家~