package com.cn.ninemax;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class JarUtils {
private String classPath;
private String className;
private String methodName;
private String[] params;
/**
* @param args
*/
public JarUtils(String classPath, String className, String methodName,
String[] params) {
this.className = className;
this.classPath = classPath;
this.methodName = methodName;
this.params = params;
}
public static void main(String[] args) {
JarUtils ju = new JarUtils("D:\\test\\22.jar",
"com.ninemax.cn.SayHello", "Say", new String[] { "Hello" });
System.out.println(ju.EexecuteMethod());
}
public Object EexecuteMethod() {
String result = "void";
File f = new File(classPath);// 通过将给定路径名字符串转换为抽象路径名来创建一个新 File 实例
URL url1 = null;
try {
url1 = f.toURI().toURL();
URLClassLoader myClassLoader = new URLClassLoader(
new URL[] { url1 }, Thread.currentThread()
.getContextClassLoader());
Class> myClass = myClassLoader.loadClass(className);
// 通过getMethods得到类中包含的方法
Method m[] = myClass.getMethods();
System.out.println(className); // 打印类名
for (int i = 0; i < m.length; i++) {
String sm = m[i].getName();
if (sm.equals(methodName)) {
if (m[i].invoke(myClass.newInstance(), params) != null) {
result = m[i].invoke(myClass.newInstance(), params)
.toString();
}
;
}
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}