javassist ClassFormatError

j2zero
  • 1
新手上路,请多包涵

题目描述

javassist生成class,添加构造方法后执行CtClass.toClass()时异常:javassist.CannotCompileException: by java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file com/example/project/BaseResponse
查看反编译输出的.class文件,复制内容到java源文件,测试是没问题的。

相关代码

<!--依赖的javassist-->
<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.24.0-GA</version>
</dependency>

Java代码

String classname = "com.example.project.BaseResponse";

ClassPool classPool = ClassPool.getDefault();

CtClass ctClass = classPool.makeClass(classname);

//添加字段
CtField resultCode = new CtField(classPool.get("java.lang.String"), "resultCode", ctClass);
resultCode.setModifiers(Modifier.PRIVATE);
ctClass.addField(resultCode);

CtField resultMsg = new CtField(classPool.get("java.lang.String"), "resultMsg", ctClass);
resultMsg.setModifiers(Modifier.PRIVATE);
ctClass.addField(resultMsg);

//添加字段的get、set方法
ctClass.addMethod(CtNewMethod.setter("setResultCode", resultCode));
ctClass.addMethod(CtNewMethod.getter("getResultCode", resultCode));

ctClass.addMethod(CtNewMethod.setter("setResultMsg", resultMsg));
ctClass.addMethod(CtNewMethod.getter("getResultMsb", resultMsg));

//添加构造方法
CtConstructor constructor = new CtConstructor(new CtClass[]{}, ctClass);
ctClass.addConstructor(constructor);

CtConstructor constructor1 = new CtConstructor(new CtClass[]{classPool.get("java.lang.String"), classPool.get("java.lang.String")}, ctClass);
constructor1.setBody("{$0.resultCode=$1;$0.resultMsg=$2;}");
ctClass.addConstructor(constructor1);

ctClass.writeFile("gen");

CtClass ctc = classPool.get(classname);
Class clz = ctc.toClass();
Object obj = clz.newInstance();

Method setResultCode = obj.getClass().getMethod("setResultCode", new Class[]{String.class});
setResultCode.invoke(obj, "1000");

Method setResultMsg = obj.getClass().getMethod("setResultMsg", new Class[]{String.class});
setResultMsg.invoke(obj, "succeed");

Method code = obj.getClass().getMethod("getResultCode");
System.out.println("resultCode:" + code.invoke(obj, null));
评论
阅读 853
1 个回答
j2zero
  • 1
新手上路,请多包涵
✓ 已被采纳

好吧,原因找到了。
即使添加的是无参数的Constructor也需要setBody,body内容为"{}"即可。

CtConstructor constructor = new CtConstructor(new CtClass[]{}, ctClass);
constructor.setBody("{}");
ctClass.addConstructor(constructor);
撰写回答

登录后参与交流、获取后续更新提醒

宣传栏