JAVA加载JAR包并调用JAR包中某个类的某个方法

JAVA加载JAR包并调用JAR包中某个类的某个方法示例如下:

package com.example;

public class Runner implements Runnable{

	public void run() {
			System.out.println("the writer is running...");
	}

}


需要将以上类打包成JAR,通过URLClassLoader读取

import org.junit.Test;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * Main
 * Created by Joker on 2017/8/16.
 */
public class Main {
    @Test
    public void test() throws Exception {
        
        URL url = new URL("file:E:/JavaJars/OtherJar/runner.jar");
        URLClassLoader urlClassLoader = new URLClassLoader(new URL[]{url}, Thread.currentThread().getContextClassLoader());
        Class clazz = urlClassLoader.loadClass("com.example.Runner");
        //Runnable runnable = (Runnable) clazz.newInstance();
        //runnable.run();
        Method method = clazz.getMethod("run");
        method.invoke(clazz.newInstance());

    }
}

通常情况下:当某个项目需要较高的扩展性时,我们会采用这种方法,一般会将项目需要灵活扩展的地方抽象出对应的接口,在写外部JAR时引入并逐一实现事前约定的好的接口。这样当系统运行时,按照配置文件载入JAR包并读取Class时,可以强转成对应接口以满足我们的需求。当然也可以通过method的invoke调用,但这种方式并不提倡。



你可能感兴趣的:(编程)