Follow below steps to add new method to a class.
Step 1: Create an instance of ClassPool.
ClassPool pool = ClassPool.getDefault();
Step 2: Create new class using makeClass method
CtClass ctClass = pool.makeClass("com.sample.app.model.Point");
Step 3: Create a method using CtMethod.
CtMethod getX = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getX", null, null, "return x;", ctClass);
Step 4: Add getX method to the class.
ctClass.addMethod(getX);
Find the below working application.
package com.sample.app;
import java.lang.reflect.Modifier;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;
import javassist.CtNewMethod;
public class App {
public static void main(String args[]) throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.makeClass("com.sample.app.model.Point");
CtField xField = new CtField(CtClass.intType, "x", ctClass);
xField.setModifiers(Modifier.PRIVATE);
CtField yField = new CtField(CtClass.intType, "y", ctClass);
yField.setModifiers(Modifier.PRIVATE);
ctClass.addField(xField);
ctClass.addField(yField);
CtMethod getX = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getX", null, null, "return x;", ctClass);
CtMethod getY = CtNewMethod.make(Modifier.PUBLIC, CtClass.intType, "getY", null, null, "return y;", ctClass);
CtMethod setX = new CtMethod(CtClass.voidType, "setX", new CtClass[] { CtClass.intType }, ctClass);
setX.setBody("{ x = $1; }");
CtMethod setY = new CtMethod(CtClass.voidType, "setY", new CtClass[] { CtClass.intType }, ctClass);
setY.setBody("{ y = $1; }");
ctClass.addMethod(getX);
ctClass.addMethod(getY);
ctClass.addMethod(setX);
ctClass.addMethod(setY);
Object obj = ctClass.toClass().newInstance();
System.out.println("Class Name : " + obj.getClass());
ctClass.writeFile("/Users/Shared/assistDemos");
}
}
Run App.java, you will get below messages in console.
Class Name : class com.sample.app.model.Point
You can observe Point.class file is generated at folder /Users/Shared/assistDemos.
$ tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
└── sample
└── app
└── model
└── Point.class
4 directories, 1 file
Open the .class file in java decompiler to see the source code.
No comments:
Post a Comment