Just specify the full class name (including package name), javassist automatically add this class to the package.
Example
CtClass demoClass = classPool.makeClass("com.sample.app.model.Demo");
Find the below working application.
App.java
package com.sample.app;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.Modifier;
public class App {
public static void main(String args[]) throws Exception {
ClassPool classPool = ClassPool.getDefault();
CtClass demoClass = classPool.makeClass("com.sample.app.model.Demo");
CtField ctField = new CtField(CtClass.doubleType, "PI", demoClass);
ctField.setModifiers(Modifier.STATIC | Modifier.FINAL | Modifier.PUBLIC);
demoClass.addField(ctField, "3.14");
demoClass.writeFile("/Users/Shared/javassist");
}
}
Run App.java.
You can observe Demo.class is created in /Users/Shared/javassist.
$tree /Users/Shared/javassist
/Users/Shared/javassist
└── com
└── sample
└── app
└── model
└── Demo.class
4 directories, 1 file
You can see the source code of Demo.class file in any Java decompiler.
No comments:
Post a Comment