通过javassist创建一个新类__javassist入门————自学笔记

关于javassist

字节码操作框架,通过javassist可以方便的操作字节码文件。搭配反射可以完成大多数java框架的底层实现

javassist获取地址


操作源码:

package com.lee.javassist;

import java.lang.reflect.Method;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewConstructor;
import javassist.CtNewMethod;
/**
 * @author Lee
 */
public class Javassist {

	public static void main(String[] args) throws Exception {
		//字节码操作创建一个类
		ClassPool cp = ClassPool.getDefault();
		CtClass cc = cp.makeClass("java.Student");
		
		//添加属性(两种方式)
		CtField cf01 = CtField.make("private int id;", cc);
		cc.addField(cf01);
		CtField cf02 = new CtField(cp.getCtClass("java.lang.String"),"name",cc);
		cc.addField(cf02);
		
		//添加Getter和Setter方法
		cc.addMethod(new CtNewMethod().setter("setId", cf01));
		cc.addMethod(new CtNewMethod().getter("getId", cf01));
		cc.addMethod(new CtNewMethod().setter("setName", cf02));
		cc.addMethod(new CtNewMethod().getter("getName", cf02));
		
		//添加自定义方法
		CtMethod cm01 = CtMethod.make("public void printInfo(){System.out.println(\"学号:\"+this.id + \"姓名:\"+this.name);}", cc);
		cc.addMethod(cm01);
		
		//添加构造方法
		CtConstructor ct01 = new CtConstructor(null, cc); //不含参
		cc.addConstructor(ct01);
		//含参构造方法
		CtConstructor ct02 = new CtNewConstructor().make("public Student(int id,String name){this.id = id;this.name = name;}",cc);
		cc.addConstructor(ct02);
		
		cc.writeFile("I:/");
		System.out.println("创建成功");
		
		
	}

}

生成的字节码文件可以通过XJad或者IDE的反编译插件查看

Student.java

package java;

public class Student {
	private int id;
	String name;

	public void setId(int arg0) {
		this.id = arg0;
	}

	public int getId() {
		return this.id;
	}

	public void setName(String arg0) {
		this.name = arg0;
	}

	public String getName() {
		return this.name;
	}

	public void printInfo() {
		System.out.println("学号:" + this.id + "姓名:" + this.name);
	}

	public Student() {
	}

	public Student(int arg0, String arg1) {
		this.id = arg0;
		this.name = arg1;
	}
}


你可能感兴趣的:(Java)