这段时间一直在看Java,看到讲 Reflection,ClassLoader,javassist 的地方,很兴奋,因为以前用.net的时候接触过一点点Reflection,但我再看到ClassLoader的时候,简直觉得非常神奇,可是神奇的东西一般都很难懂,看了很多资料,都不太明白,直到在ibm的网站上看到《java编程的动态性》,很具体的阐述了ClassLoader的作用,接着我看了使用javassist修改字节码的地方,跃跃欲试,动手做了一个小小的例子,朋友说我误入歧途,刚刚接触java就看这个东西,呵呵,不多说,看看代码就知道了。
AddMethod.java
/*
* Created on 2004-9-24
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package cn.cpX.Parco.AddMethod;
import java.lang.reflect.*;
import javassist.*;
/**
* @author cpX.Parco
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class AddMethod {
/**
*
*/
public AddMethod() {
super();
// TODO Auto-generated constrUCtor stub
}
private static void addMethod(CtClass clas)
{
try
{
String strOldMethod = "outputHello";
String strNewMethod = strOldMethod + "2";
/* //add new Method (copy)
* StringBuffer newMethodBody = new StringBuffer();
* CtMethod oldMethod = clas.getDeclaredMethod(strOldMethod);
* CtMethod newMethod = CtNewMethod.copy(oldMethod, strNewMethod, clas, null);
* newMethodBody.append("{System.out.println(\"Hello\");}");
* newMethod.setBody(newMethodBody.toString());
* clas.addMethod(newMethod);
*/
//add new Method (create)
CtClass []arrClas = new CtClass[0];
CtClass []arrExce = new CtClass[0];
StringBuffer newMethodBody = new StringBuffer();
newMethodBody.append("{System.out.println(\"Hello\");}");
CtMethod newMethod = CtNewMethod.make(CtClass.voidType ,strNewMethod, arrClas, arrExce, newMethodBody.toString(), clas);
clas.addMethod(newMethod);
//invoke new Method
Class tmpClass = clas.toClass();
Object obj = tmpClass.newInstance();
Method method = tmpClass.getDeclaredMethod(strNewMethod, null);
method.invoke(obj, null);
}
catch(Exception e)
{
e.printStackTrace();
}