javassist case

一个普通的类,一个 name 属性, 只有 getter 方法,木有 setter.

package org.alex.cases.javassist;

public class TestClass
{
	private String name;
	
	public String getName()
	{
		return name;
	}
}


利用 javassist 重写 TestClass 类.

package org.alex.cases.javassist;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javassist.CannotCompileException;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class TestJavassist
{
	public static void main(String[] args) throws NotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, CannotCompileException,
			IOException, NoSuchMethodException, SecurityException
	{
		ClassPool pool = ClassPool.getDefault();
		CtClass cc = pool.get("org.alex.cases.javassist.TestClass");
		CtMethod setNameMethod = CtMethod.make("public void setName(String name){this.name = $1;}", cc);
		cc.addMethod(setNameMethod);

		cc.writeFile();

		@SuppressWarnings("unchecked")
		Class<TestClass> c = cc.toClass();
		TestClass instance = (TestClass) c.newInstance();

		Method method = c.getMethod("setName", String.class);
		method.invoke(instance, "a");

		System.out.println(instance.getName());
	}
}



		<dependency>
			<groupId>org.javassist</groupId>
			<artifactId>javassist</artifactId>
			<version>3.17.1-GA</version>
		</dependency>

你可能感兴趣的:(java)