我正在尝试编写方法来更改类型化元素的类型。localVar
我有需要更改的 CtLocalVariable 。
我的方法是:
private void changeType(CtTypedElement<?> typedElem) {
CtTypeReference<?> type = typedElem.getType();
Optional<Class<?>> substituteOpt = TypeMapping.getSubstituteClass(type.getActualClass());
substituteOpt.ifPresent(clazz -> {
final CtTypeReference<?> newType = getFactory().Code().createCtTypeReference(clazz);
typedElem.setType(newType);
});
}
LineTypeMapping.getSubstituteClass(type.getActualClass());
只返回当前局部变量类型的替代类型。当然typedElem.setType(newType);
有编译错误。
然后我尝试了这个,它也给出了编译错误:
CtTypeReference<?> type = typedElem.getType();
typedElem.setType(type);
现在我不知道这是正确的路径还是我应该尝试更改局部变量的声明并更改整个局部变量而不仅仅是现有的类型。
编译的唯一示例是:
private <T> void changeType(CtTypedElement<T> typedElem) {
CtTypeReference<T> type = typedElem.getType();
typedElem.setType(type);
Optional<Class<?>> substituteOpt = TypeMapping.getSubstituteClass(type.getActualClass());
substituteOpt.ifPresent(clazz -> {
final CtTypeReference<T> newType = getFactory().Code().createCtTypeReference(clazz);
typedElem.setType(newType);
});
}
但这对我来说在语义上是不正确的,因为它们是两种不同的类型(type
和newType
)。