gds通用软件开发系统

导航

JAVA动态加载JAR包执行程序

入口代码

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import dynamic.test.ICarFactory;

public class hello {
public static void main(String args[])
{
    System.out.println("Hello world");
    // JAR文件地址
    String jarName = "CarFactory.jar";
    ICarFactory icf=null;
    
    //命名空间 类名称
    String className="dynamic.test.BYDFactory";
    
    File file = new File(jarName);
    URL url=null;
    try {
        url = file.toURL();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    
    URLClassLoader loader = new URLClassLoader(new URL[]{url});
    Class aClass=null;
    try {
        // 接口实例化
        aClass = loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
 
    try {
        icf = (ICarFactory)aClass.newInstance();
    } catch (InstantiationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    icf.makeCar();
}
}

接口类

package dynamic.test;
public interface ICarFactory {
    public void makeCar();//等待实现的造车方法
}

实现类

//创建BMWFactory类,实现了ICarFactory
package dynamic.test;
public class BMWFactory implements ICarFactory {
//实现了ICarFactory的makeCar()方法
public void makeCar() {
System.out.println("BMWFactroy made a 宝马  for you");
}
}
//创建BYDFactory类,实现了ICarFactory
package dynamic.test;
public class BYDFactory implements ICarFactory {
//实现了ICarFactory的makeCar()方法
public void makeCar() {
System.out.println("BYDFactroy 生产  一辆  比亚迪  for you");
}
}

 

posted on 2014-04-08 14:01  gds通用软件开发系统  阅读(640)  评论(0编辑  收藏  举报