如何克服访问者实现的类型擦除问题
在 C# 和 C++ 的一些项目之后,我开始使用 Java。
我想设计这样的访问者界面:
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> //....
{
}
当然,由于类型擦除,这不起作用。 (我想要这样的东西的原因是,我将为可以访问的不同操作组提供不同的访问者接口。)
我想到的唯一解决方案是声明接口
public interface ActionAVisitor {
void visitAction(ActionA action);
}
public interface ActionBVisitor {
void visitAction(ActionB action);
}
//...
,然后
public interface MySmallActionVisitor
extends ActionAVisitor, ActionBVisitor
{
}
这会起作用,但我不会不喜欢所有 ActionXVisitor-Interfaces 的声明,这是愚蠢的重复和大量文件...
您有什么想法如何做得更好吗?
多谢!
I am starting to work with Java after some projects in C# and C++.
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.)
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...
Do you have any ideas how to do this better?
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我使用 Java 中的一个大型且复杂的库,该库以非常干净整洁的方式广泛使用访问者模式。特别是,我遇到了同样的类型擦除问题,现在已经解决了。
如果您有机会,请查看 我写过一篇关于此的文章。
这是一篇很长的文章,从概念上详细解释了访问者模式的含义,并且在文章的最后部分讨论了一个涉及多态性和类型擦除的现实生活示例。
干杯
I work with a large and complex library in Java which extensively uses the Visitor Pattern in a very clean and neat way. 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
我将使用单个非参数化访问者接口,然后在访问者方法内根据类型进行调度。
I would use a single unparameterized visitor interface, then inside the visitor method do the dispatch based on type.
没有办法能够避免方法内部的instanceof。但你可以让它更优雅:
}
There's no way to be able to avoid instanceof of inside the method. But you can make it more graceful:
}