修复此铸件行为的最干净方法 [英] Cleanest way to fix this castings behavior

查看:88
本文介绍了修复此铸件行为的最干净方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我有一个列表,其中包含50种不同类型的Node的某些子类,我希望它们是同一类型,否则将得到ClassException.我有一个接收此列表的方法,以及一个持有并占有某种类型的节点的方法

Imagine I have a list with 50 different type of a certain subclasses of Node which I expect to be the same type or get a ClassException if not. I have a method which receives this list and a node holding and expeting a certain type

我想做这样的事情:

public <E extends Node> receive(List<Node> list, Node<E extends Node> node){
    for (Node element : list ){
         node.addElement((E) element); //Type erasure, if you put wrong node no CastException in Runtime 
    }
}

但请避免这样做:

public <E extends Node> receive(List<Node> list, Node<E extends Node> node){
    for (Node element : list ){
         if      (element instanceof SubNode1) node.addElement((Subnode1) element); 
         else if (element instanceof SubNode2) node.addElement((Subnode2) element);
         //(...)
         else if (element instanceof SubNode50) node.addElement((Subnode50) element);
    }
}

如果我不能转换为泛型,那么做这样的事情会很棒:

If I cannot cast to generic it would be great doing something like this:

public <E extends Node> receive(List<Node> list, Node<E extends Node> node){
    for (Node element : list ){
         node.addElement(element.autoDowncastToSubClassOf("Node"));
    }
}

所有这些选项都考虑到了node.addElement(E node),因此也期望E.我考虑过更改它以接受任何种类的Node并进行转换.但随后会发生以下情况:为什么列表<类型>在编译和执行时吸收非类型元素?

All this options are taking into account node.addElement(E node), so is expecting E. I thought of changing this for accepting any kind of Node and make the cast. But then it happens this: Why a List<type> absorbs not-type element in compilation and execution time?

我应该放弃第二种方法吗?

Should I discard this second approach?

推荐答案

由于没有答案,在经过大量研究并以不同方式关注该主题之后,这里提供了线索,我指出了预期的解决方案:

As there are no answers for this and the clue is given here after a lot of research and focusing the topic in different ways, I point to the expected solution:

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆