需要两个类,用于下面的测试
class="java" name="code">package test;
public interface IProcess {
public void process();
}
package test;
public class Process implements IProcess{
public void process() {
System.out.println("实际处理器开始执行!");
}
}
反射的
例子,forName方法
// 根据classname来生成对象
动态加载jar的方式类似
private static class JarLoader {
private URLClassLoader urlClassLoader;
public JarLoader(URLClassLoader urlClassLoader) {
this.urlClassLoader = urlClassLoader;
}
public void loadJar(URL url) throws Exception {
Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addURL.setAccessible(true);
addURL.invoke(urlClassLoader, url);
}
}
private static void loadjar(JarLoader jarLoader, String path) throws MalformedURLException, Exception{
File libdir = new File(path);
if (libdir != null && libdir.isDirectory()) {
File[] listFiles = libdir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
return file.exists() && file.isFile() && file.getName().endsWith(".jar");
}
});
for (File file : listFiles) {
jarLoader.loadJar(file.toURI().toURL());
}
}else{
System.out.println("[Console Message] Directory ["+path+"] does not exsit, please check it");
System.exit(0);
}
}
public static void main(String[] args) {
JarLoader jarLoader = new JarLoader((URLClassLoader)ClassLoader.getSystemClassLoader());
loadjar(jarLoader, System.getProperty("user.dir")+"/lib");
}
@SuppressWarnings("unchecked")
public static <U extends IProcess> U getObjectAsClassName(String className) {
U proess = null;
try {
proess = (U) Class.forName(className).newInstance();
// proess.process();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return proess;
}
根据方法名执行方法
public static void callMehod(String methodName, Process p) {
Method[] methods = Process.class.getMethods();
for (Method method : methods) {
if (method.getName().equals(methodName)) {
// 找到方法,执行
try {
method.invoke(p, new Object[] {});
} 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();
}
}
}
}
代理,一个
接口java.lang.reflect.InvocationHandler,和一个java.lang.reflect.Proxy类
Proxy用来生成生成一个代理类,InvocationHandler用于处理实际其他逻辑和调用被代理者,例子:
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
/**
* 处理器代理,这个类实现了InvocationHandler
*
*/
public class ProcessProxy implements InvocationHandler {
private Object targs;
public ProcessProxy(Object targs) {
this.targs = targs;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
System.out.println("被代理对象执行前");
Object ret = method.invoke(targs, args);
System.out.println("被代理对象执行后");
return ret;
}
}
生成代理类已经代理类实例。
@SuppressWarnings("unchecked")
public static <U extends IProcess> U getProxyProcess(Object process) {
ProcessProxy pp = new ProcessProxy(process);
return (U) Proxy.newProxyInstance(Process.class.getClassLoader(),
Process.class.getInterfaces(), pp);
}
JAVA动态技术,原理,生成一个java文件,将这个生成的java文件加载
内存
// 生成动态类
@SuppressWarnings("unchecked")
public static IProcess makeDynamicClassObject(IProcess p) {
String _package = "package test;\r\n";
String classDefine = "public class DynamicClass implements IProcess {"
+ "\r\n" + "private IProcess p;" +
"public DynamicClass(IProcess p) {" + "this.p = p;" + "}" +
"public void process() {"
+ "System.out.println(\"动态生成的java类,开始执行\");" + "p.process();"
+ "}" + "}";
String javaSourceCode = _package + classDefine;
String fileName = System.getProperty("user.dir")
+ "/src/test/DynamicClass.java"; // 设置一个路径
File javaFile = new File(fileName);
try {
// 写入java文件
FileWriter outFile = new FileWriter(javaFile);
outFile.write(javaSourceCode);
outFile.flush();
outFile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 写入完毕,开始生成class文件(编译)
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileMang = compiler.getStandardFileManager(
null, null, Charset.forName("utf-8"));
Iterable<? extends JavaFileObject> units = fileMang
.getJavaFileObjects(fileName);
CompilationTask t = compiler.getTask(null, fileMang, null, null, null,
units);
t.call();
try {
fileMang.close();
javaFile.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
URLClassLoader uloader = new URLClassLoader(new URL[] { new URL(
"file://" + System.getProperty("user.dir") + "/src/") });
try {
//编译完成,加载
Class c = uloader.loadClass("test.DynamicClass");
//创建实例
return (IProcess) c.getConstructor(IProcess.class).newInstance(
p);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException 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 (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
动态加载jar的方式类似
private static class JarLoader {
private URLClassLoader urlClassLoader;
public JarLoader(URLClassLoader urlClassLoader) {
this.urlClassLoader = urlClassLoader;
}
public void loadJar(URL url) throws Exception {
Method addURL = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
addURL.setAccessible(true);
addURL.invoke(urlClassLoader, url);
}
}
private static void loadjar(JarLoader jarLoader, String path) throws MalformedURLException, Exception{
File libdir = new File(path);
if (libdir != null && libdir.isDirectory()) {
File[] listFiles = libdir.listFiles(new FileFilter() {
@Override
public boolean accept(File file) {
// TODO Auto-generated method stub
return file.exists() && file.isFile() && file.getName().endsWith(".jar");
}
});
for (File file : listFiles) {
jarLoader.loadJar(file.toURI().toURL());
}
}else{
System.out.println("[Console Message] Directory ["+path+"] does not exsit, please check it");
System.exit(0);
}
}
public static void main(String[] args) {
JarLoader jarLoader = new JarLoader((URLClassLoader)ClassLoader.getSystemClassLoader());
loadjar(jarLoader, System.getProperty("user.dir")+"/lib");
}