简体   繁体   English

如何克服访问者实施的类型擦除问题

[英]How to overcome problem with type erasure for visitor implementation

I am starting to work with Java after some projects in C# and C++. 在C#和C ++中的一些项目之后,我开始使用Java。

I wanted to design visitor interfaces like this: 我想设计这样的访问者界面:

public interface ActionVisitor<A> {
    void visitAction(A action);    
}

public interface MySmallActionVisitor 
extends ActionVisitor<ActionA>,
    ActionVisitor<ActionB>
{

}

public interface MyFullActionVisitor 
extends ActionVisitor<ActionA>,
    ActionVisitor<ActionB>,ActionVisitor<ActionC>,ActionVisitor<ActionD> //....
{

}

Of course this doesn't work because of type erasure. 当然,由于类型擦除,这不起作用。 (The reason why I want something like this is that I will have different Visitor interfaces for different groups of Actions that can be visited.) (我想要这样的东西的原因是我将为可以访问的不同Actions组设置不同的Visitor接口。)

The only solution that comes to my mind is to declare interfaces 我想到的唯一解决方案是声明接口

public interface ActionAVisitor {
        void visitAction(ActionA action);    
    }
public interface ActionBVisitor {
        void visitAction(ActionB action);    
    }
//...

and then 接着

public interface MySmallActionVisitor 
extends ActionAVisitor, ActionBVisitor
{

}

This would work, but I wouldn't like the declaration of all the ActionXVisitor-Interfaces which is stupid repetition and lots of files... 这可行,但我不想声明所有的ActionXVisitor接口,这是愚蠢的重复和大量的文件......

Do you have any ideas how to do this better? 你有什么想法如何更好地做到这一点?

Thanks a lot! 非常感谢!

I work with a large and complex library in Java which extensively uses the Visitor Pattern in a very clean and neat way. 我使用Java中的大型复杂库,它以非常干净和整洁的方式广泛使用访问者模式。 In particular, I came across with the same problem of type erasure and it is solved now. 特别是,我遇到了类型擦除的相同问题,现在已经解决了。

If you have a chance, please have a look at an article I've written about this . 如果你有机会,请看一篇我写过的文章

It's a long article, which explains in detail what the Visitor pattern is about conceptually and, in last part of the article, it is discussed a real life example which involves polymorphism and type erasure. 这是一篇很长的文章,详细解释了访问者模式在概念上的含义,在本文的最后部分,讨论了涉及多态性和类型擦除的现实生活示例。

Cheers 干杯

我会使用一个未参数化的访问者界面,然后在访问者方法内部根据类型进行调度。

There's no way to be able to avoid instanceof of inside the method. 没有办法能够避免方法内部的instanceof。 But you can make it more graceful: 但你可以使它更优雅:

public interface MarkerInterface{}

public interface ActionVisitor<T extends MarkerInterface> {
void visitAction(T action);}

public class A implements MarkerInterface{}

public class B implements MarkerInterface{}

public class MySmallActionVisitor implements ActionVisitor<MarkerInterface>{

@Override
public void visitAction(MarkerInterface action) {
    if(action instanceof A){

    }
    else if(action instanceof B){

    }
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM