java 调用jar包


package com.test;

public class Plus {
    public double plus(double d1, double d2) {
        return d1+d2;
    }


import java.net.URL;
import java.net.URLClassLoader;

public class MyClassLoader extends URLClassLoader {
    public MyClassLoader() {
        super(new URL[0]);
    }

    public void loadJar(String str) {
        try {
            URL url = new URL(str);
            addURL(url);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public Class<?> findClass(String name) throws ClassNotFoundException {
        return super.findClass(name);
    }

    public Object invokeMethod(Class<?> clazz, String methodName,
            Class<?>[] parametersTypes, Object[] args) throws Exception {
        Object obj = clazz.newInstance();
        Method method = clazz.getMethod(methodName, parametersTypes);
        Object result = method.invoke(obj, args);
        return result;
    }

    public static void main(String[] args) {
        MyClassLoader loader = new MyClassLoader();
        loader.loadJar("file:///D:/mylib.jar");
        try {
            Class<?> clazz = loader.findClass("com.test.Plus");
            Object result = loader.invokeMethod(clazz, "plus", new Class[] {
                    Double.TYPE, Double.TYPE }, new Object[] {
                    Double.valueOf("100"), Double.valueOf("200") });
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(java)