Step 1: Instantiate ClassPool.
ClassPool pool = ClassPool.getDefault();
Step 2: Get CtClass instance.
CtClass ctClass = pool.get("com.sample.app.model.Employee");
Step 3: Define methods.
CtMethod getSalary = CtNewMethod.make(Modifier.PUBLIC, CtClass.doubleType, "getSalary", null, null, "return salary;", ctClass);
CtMethod setSalary = new CtMethod(CtClass.voidType, "setSalary", new CtClass[] { CtClass.doubleType }, ctClass);
setSalary.setBody("{ salary = $1; }");
Step 4: Add methods to CtClass instance.
ctClass.addMethod(getSalary);
ctClass.addMethod(setSalary);
Find the below working application.
package com.sample.app.model;
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
App.java
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.get("com.sample.app.model.Employee");
// Add salary field
CtField ctField = new CtField(CtClass.doubleType, "salary", ctClass);
ctField.setModifiers(Modifier.PUBLIC);
ctClass.addField(ctField);
// Add getters and setters for salary
CtMethod getSalary = CtNewMethod.make(Modifier.PUBLIC, CtClass.doubleType, "getSalary", null, null,
"return salary;", ctClass);
CtMethod setSalary = new CtMethod(CtClass.voidType, "setSalary", new CtClass[] { CtClass.doubleType }, ctClass);
setSalary.setBody("{ salary = $1; }");
ctClass.addMethod(getSalary);
ctClass.addMethod(setSalary);
ctClass.writeFile("/Users/Shared/assistDemos");
}
}
Run App.java.
You can observe Employee.class file is generated at folder /Users/Shared/assistDemos.
$tree /Users/Shared/assistDemos
/Users/Shared/assistDemos
└── com
└── sample
└── app
└── model
└── Employee.class
4 directories, 1 file
Open Employee.class file in java decompiler to see the source code.
No comments:
Post a Comment