javassist case_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > javassist case

javassist case

 2013/7/29 22:09:24  id.alex  程序员俱乐部  我要评论(0)
  • 摘要:一个普通的类,一个name属性,只有getter方法,木有setter.packageorg.alex.cases.javassist;publicclassTestClass{privateStringname;publicStringgetName(){returnname;}}利用javassist重写TestClass类.packageorg.alex.cases.javassist;importjava.io.IOException;importjava.lang.reflect
  • 标签:Java ASE
一个普通的类,一个 name 属性, 只有 getter 方法,木有 setter.

class="java" name="code">
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 = name;}", 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>
上一篇: 计算机书封面也疯狂 下一篇: 没有下一篇了!
发表评论
用户名: 匿名