我第一次尝试使用Javassist,而且我被卡住了。 我在运行时创建类,如果有任何新字段,我想在运行时更改类。 我的代码在下面
public static Class generate(String className, Map<String, Class<?>> properties) throws NotFoundException,
CannotCompileException, ClassNotFoundException {
ClassPool pool = ClassPool.getDefault();
CtClass cc=null;
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null)
{
pool.insertClassPath(new LoaderClassPath(contextClassLoader));
}
try{
cc = pool.makeClass(className);
cc.defrost();
cc.addInterface(resolveCtClass(Serializable.class));
for (Entry<String, Class<?>> entry : properties.entrySet()) {
//add feilds
// add getter
// add setter
}
cc.addConstructor(generateConstructor(cc,properties,className));
CtConstructor defaultCons=new CtConstructor(NO_ARGS, cc);
defaultCons.setBody(";");
cc.addConstructor(defaultCons);
return cc.toClass();
}catch(Exception e){
cc = pool.get(className);
for (Entry<String, Class<?>> entry : properties.entrySet()) {
try{
//add feilds
// add getter
// add setter
}catch(Exception e1){
System.out.println("Fields or method already present");
}
}
try{
cc.addConstructor(generateConstructor(cc,properties,className));
}catch(Exception e1){
System.out.println("Constructor already present");
}
try {
byte[] classFile = cc.toBytecode();
HotSwapper hs = new HotSwapper(9080);
hs.reload(className, classFile);
} catch (IOException | IllegalConnectorArgumentsException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return Class.forName(className);
}
此代码无效。 我收到了以下错误
java.lang.ClassNotFoundException:com.sun.jdi.connect.IllegalConnectorArgumentsException
答案 0 :(得分:0)
您必须在项目中添加以下依赖项
<!-- https://mvnrepository.com/artifact/com.sun/tools -->
<dependency>
<groupId>com.sun</groupId>
<artifactId>tools</artifactId>
<version>1.7.0.13</version>
<!--<scope>system</scope>-->
</dependency>