编译 Java 代码时发生'incompatible types error'



它是一个Spring Boot应用程序。我不知道如何使代码正确编译。

public class JavassistGenerator implements Generator {
@SuppressWarnings("unchecked")
@Override
public <T extends Enum, C extends UntypedStateMachine> Class<C> gen(Class<T> eventType) throws Exception {
ClassPool pool = ClassPool.getDefault();
ClassClassPath classPath = new ClassClassPath(this.getClass());
pool.insertClassPath(classPath);
CtClass cc = pool.makeClass(eventType.getName() + "$StateMachine");
ClassFile ccFile = cc.getClassFile();
ConstPool constPool = ccFile.getConstPool();
//继承
cc.setSuperclass(pool.get("com.youzan.pay.hvp.common.sm.generator.AbstractStateMachineExt"));
// 添加类注解
AnnotationsAttribute bodyAttr = new AnnotationsAttribute(constPool, AnnotationsAttribute.visibleTag);
Annotation bodyAnnot = new Annotation("org.squirrelframework.foundation.fsm.annotation.StateMachineParameters", constPool);
bodyAnnot.addMemberValue("stateType", new ClassMemberValue("java.lang.String", constPool));
bodyAnnot.addMemberValue("eventType", new ClassMemberValue(eventType.getName(), constPool));
bodyAnnot.addMemberValue("contextType", new ClassMemberValue(BizContextParam.class.getName(), constPool));
bodyAttr.addAnnotation(bodyAnnot);
ccFile.addAttribute(bodyAttr);
return cc.toClass();// error occur this line 
}
}

错误消息:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.0:compile (default-compile) on project pay-hvp-common: Compilation failure
[ERROR] /Users/ykwoo001/Documents/work/codes/pay-hvp/pay-hvp-common/src/main/java/com/youzan/pay/hvp/common/sm/generator/JavassistGenerator.java:[42,26] 不兼容的类型: java.lang.Class<capture#1, 共 ?>无法转换为java.lang.Class<C>
[ERROR] -> [Help 1]

CtClass#toClass(在编译时(返回一个Class<? >,无论您使用CtClass#setSuperClass设置了什么超类,编译器都不知道实际的超类。

在运行时,生成的类是AbstractStateMachineExt的子类型,但在编译时不是。

您有两种解决方案。

您可以只返回一个Class<? >:

public <T extends Enum> Class<?> gen(Class<T> eventType) throws Exception {

或者使用未检查的强制转换:

return (Class<C>) cc.toClass();

相关内容

最新更新