Step 1: Instantiate ClassPool object.
Employee.java
Previous
Next
Home
ClassPool pool = ClassPool.getDefault();
Step 2: Get CtClass instance
CtClass ctClass = pool.get("com.sample.app.model.Employee");
Step 3: Define a field
CtField ctField = new CtField(CtClass.doubleType, "salary", ctClass);
ctField.setModifiers(Modifier.PUBLIC);
Step 4: Add this field to CtClass instace.
ctClass.addField(ctField);
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;
public class App {
public static void main(String args[]) throws Exception {
ClassPool pool = ClassPool.getDefault();
CtClass ctClass = pool.get("com.sample.app.model.Employee");
CtField ctField = new CtField(CtClass.doubleType, "salary", ctClass);
ctField.setModifiers(Modifier.PUBLIC);
ctClass.addField(ctField);
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