Java反射机制动态加载-通俗易懂

编译/运行

  1. 编译时是静态加载,如我们的new();
  2. 运行时是动态加载,Class.forName();

Demo走起

class Main  
{
    public static void main(String[] args) throws Exception
    {
        if("Excel".equals(args[0])){
            Excel excel = new Excel();
            excel.start();
        }
        if("Office".equals(args[0])){
            Office office = new Office();
            office.start();
        }
    }
}

用Editplus写的,然后我们进行编译
这里写图片描述
编译是静态的,其实我们并不是所有的类都要用到,比如我们只要用Excel,n那Office应该此时不需要编译。

动态加载

class Main  
{
    public static void main(String[] args) throws Exception
    {
        Class c = Class.forName(args[0]);
        Cxx e = (Cxx)c.newInstance();
        e.start();
    }
}   

//接口
interface Cxx
{
    public void start();
}

//Excel类并实现接口
class Excel implements Cxx
{
    public void start(){
        System.out.println("excel start");
    }
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/m0_37499059/article/details/80459795