【发布时间】:2019-06-23 19:50:58
【问题描述】:
我正在使用框架AbstractProcessor<T extends CtElement>的通用抽象类,它基本上是一个访问所有元素T的访问者。有一个方法
public void process(T element)
作用于指定类型的所有元素并做某事。
然后我有这个AbstractProcessor 的具体类实现,我使用某种工厂模式创建,同时持有一个公共超类型AbstractProcessor 的列表,然后通过它们的多态性调用process 方法。这些具体类之一可能类似于XYZProcessor<T extends CtElement> extends AbstractProcessor<T>。
我现在创建这些具体的处理器,例如new XYZProcessor<CtNamedElement>(),其中CtNamedElement 是CtElement 的子类型,因此XYZProcessor 的process 方法只能使用CTNamedElements 调用。但是process-method 似乎被所有CtElement 类型的访问元素调用,而不仅仅是我想要的CtNamedElement 类型的元素。
有人知道这里发生了什么吗?
编辑:相关代码:
创建这样的处理器
case CLASS:
//CtClass is subtype of CtNamedElement
this.setProcessor(new AnnotatedWithProcessor<CtClass>(targetName, attributeMappings, metapackage));
break;
类定义:
public class AnnotatedWithProcessor<T extends CtNamedElement> extends AbstractProcessor<T> {
@Override
public void process(T element) {
//do stuff here with elements of correct type
}
然后像这样调用处理器:
//this gets set with a concrete case like above
AbstractProcessor<?> processor;
...
//this astModel gets processed with the respective processor,
//where I expect the process method only getting called for the correct types (in this case only when coming over elements of type CtClass),
//but the method gets called for all types of CtNamedElement, not only for those of type CtClass
this.astModel.processWith(processor);
【问题讨论】:
-
请分享相关代码。
-
在原问题中添加了相关代码
标签: java generics polymorphism visitor-pattern