Load jar and dynamically create object from it

Two maven project, project A load the project B jar, create the object dynamically and invoke the method

Project A:

public interface MyInterface {
	public void play();
}

Project A:

package hk.quantr.projectb;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.commons.io.IOUtils;

public class ProjectB {

	public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		String jarPath = Paths.get("../projectA/target/projectA-1.0.jar").toString();
		JarFile jarFile = new JarFile(jarPath);
		Enumeration<JarEntry> e = jarFile.entries();

		URL[] urls = {new URL("jar:file:" + jarPath + "!/")};
		URLClassLoader cl = URLClassLoader.newInstance(urls);

		while (e.hasMoreElements()) {
			JarEntry je = e.nextElement();
			System.out.println(">" + je);
			if (je.getName().equals("META-INF/MANIFEST.MF")) {
				InputStream input = jarFile.getInputStream(je);
				String content = IOUtils.toString(input, "utf-8");
				System.out.println(content);
			}
			if (je.getName().equals("component.xml")) {
				System.out.println("-".repeat(100));
				InputStream input = jarFile.getInputStream(je);
				String content = IOUtils.toString(input, "utf-8");
				System.out.println(content);
				System.out.println("-".repeat(100));
			}
			if (je.isDirectory() || !je.getName().endsWith(".class")) {
				continue;
			}
			String className = je.getName().substring(0, je.getName().length() - 6);
			className = className.replace('/', '.');
			Class c = cl.loadClass(className);
			MyInterface clsInstance = (MyInterface) c.newInstance();
			clsInstance.play();
		}
	}
}

Project B:

public class Project2 implements MyInterface {

	@Override
	public void play() {
		System.out.println("play project 2");
	}

}

Leave a Reply

Your email address will not be published. Required fields are marked *