大家好,我一直在 javassist 图书馆尝试我的双手,似乎遇到了我无法跨越的障碍。问题是我想动态创建一个配置类来扩展球衣的 ResourceConfig 类,并且在构造函数中我想注册包和工厂对象以进行注入。但每次我得到错误(发布在下面)
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
ClassPool pool = ClassPool.getDefault();
CtClass superCc = null;
try {
superCc = pool.get(ResourceConfig.class.getCanonicalName());
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
CtClass cc = pool.makeClass("org.demonking.AppConfig");
cc.setSuperclass(superCc);
System.out.println(cc.getSuperclass().getName());
CtConstructor constructor = new CtConstructor(new CtClass[0], cc);
constructor.setBody("{\n"+"packages(\"org.demonking\");"+"\n"+"register(InjectorDemo.class);"+"\n"+"}");
cc.addConstructor(constructor);
} catch (CannotCompileException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//rest of my jersey code
}
我想动态创建的原始 AppConfig(工作正常)
public class AppConfig extends ResourceConfig{
public AppConfig()
{
packages("org.demonking");
register(new AbstractBinder(){
@Override
protected void configure() {
bindFactory(ContextHelperFactory.class)
.to(ContextHelper.class)
.in(RequestScoped.class);
}
});
}
请注意,在研究时我发现 javassist 对匿名内部类有一些限制,因此代码已转移到 InjectorDemo 类。
public class InjectorDemo extends AbstractBinder {
@Override
protected void configure() {
// TODO Auto-generated method stub
bindFactory(ContextHelperFactory.class)
.to(ContextHelper.class)
.in(RequestScoped.class);
}
}
jeck猫
相关分类