问题
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
I would like to do something like this:
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
}
}
but avoid doing this:
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"));
}
}
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?
回答1:
Assuming that a particular class of Node always takes its own class of node as elements,
Supposed you have a class or interface like:
class Node<E> {
public void addSubElement(E node) { ... }
}
and then your Node classes are all like this:
class Subnode1 extends Node<Subnode1>
Then you can perhaps write your method like this:
public <E extends Node<E>> receive(List<Node<?>> list, E node){
for (Node<?> element : list) {
node.addElement(node.getClass().cast(element));
}
}
回答2:
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:
How can I downcast to class' type E or at least make it in a safe way without warnings?
来源:https://stackoverflow.com/questions/11601200/cleanest-way-to-fix-this-castings-behavior