您需要先加载您的 jar,然后从那里加载所需的类。
URL myJarFile = new URL("jar","","file:"+jarPath);
URLClassLoader child = new URLClassLoader (myJarFile , this.getClass().getClassLoader());
Class classToLoad = Class.forName ("com.MyClass", true, child);
Method method = classToLoad.getDeclaredMethod ("myMethod");
Object instance = classToLoad.newInstance ();
Object result = method.invoke (instance);
然后可以先获取jar文件中所有类的列表:
List<String> classNames=new ArrayList<String>();
ZipInputStream zip=new ZipInputStream(new FileInputStream("/path/to/jar/file.jar"));
for(ZipEntry entry=zip.getNextEntry();entry!=null;entry=zip.getNextEntry())
if(entry.getName().endsWith(".class") && !entry.isDirectory()) {
StringBuilder className=new StringBuilder();
for(String part : entry.getName().split("/")) {
if(className.length() != 0)
className.append(".");
className.append(part);
if(part.endsWith(".class"))
className.setLength(className.length()-".class".length());
}
classNames.add(className.toString());
}
获得课程列表后,请执行以下操作:
File file = new File("Absolute Path to your jar");
URL url = file.toURI().toURL();
URL[] urls = {url};
ClassLoader loader = new URLClassLoader(urls);
Class myClass = loader.loadClass(classNames.get(0));
System.out.println("Executing...");
Object tester = myClass.newInstance();
System.out.println("Test");