javaassist 的使用

1
查看版本号:


F:\bisoft\ext\javassist-3.11.GA\javassist-3.11.0>java -jar javassist.jar
Javassist version 3.11.0.GA
Copyright (C) 1999-2009 Shigeru Chiba. All Rights Reserved.

F:\bisoft\ext\javassist-3.11.GA\javassist-3.11.0>


2
Dump CLASS

package cn.bisoft.java.util.test;

import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.PrintWriter;

import javassist.bytecode.ClassFile;
import javassist.bytecode.ClassFileWriter;

public class ClassDumpUtil
{
public static void dump(String classFilePath) throws Exception
{
DataInputStream in = new DataInputStream(new FileInputStream(classFilePath));
ClassFile w = new ClassFile(in);
PrintWriter out = new PrintWriter(System.out, true);
out.println("*** constant pool ***");
w.getConstPool().print(out);
out.println();
out.println("*** members ***");
ClassFileWriter.print(w, out);
}

public static void main(String[] args) throws Exception {

ClassDumpUtil.dump("E:/bisoft/code/workspace/bisoft/build/classes/cn/bisoft/java/core/F.class");
}
}




3
javassist.jar 依赖 JDK/LIB/tools.jar

导入示例:
src -/
example +

4
示例1:
Test.java

增加一个不存在的方法到类g()中.

package sample;

import javassist.*;

public class Test
{
public int f(int i)
{
return i + 1;
}

public static void main(String[] args) throws Exception
{
ClassPool pool = ClassPool.getDefault();

CtClass cc = pool.get("sample.Test");
try
{
cc.getDeclaredMethod("g");
System.out.println("g() is already defined in sample.Test.");
}
catch (NotFoundException e)
{
/*
* getDeclaredMethod() throws an exception if g() is not defined in sample.Test.
*/
CtMethod fMethod = cc.getDeclaredMethod("f");
CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null);
cc.addMethod(gMethod);
cc.writeFile(); // update the class file
System.out.println("g() was added.");
}
}
}




运行后:

g() was added.

验证结果:
a. class 的修改时间已经修改
b. 反编译 class 文件 ,查看源码已经修改


package sample;

import java.io.PrintStream;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.CtNewMethod;
import javassist.NotFoundException;

public class Test
{
public int f(int i)
{
return (i + 1);
}

public static void main(String[] args) throws Exception {
ClassPool pool = ClassPool.getDefault();

CtClass cc = pool.get("sample.Test");
try {
cc.getDeclaredMethod("g");
System.out.println("g() is already defined in sample.Test.");
}
catch (NotFoundException e)
{
CtMethod fMethod = cc.getDeclaredMethod("f");
CtMethod gMethod = CtNewMethod.copy(fMethod, "g", cc, null);
cc.addMethod(gMethod);
cc.writeFile();
System.out.println("g() was added.");
}
}

[b] public int g(int i)
{
return (i + 1);
}
[/b]
}




5
例子2

你可能感兴趣的:(Java,EE)