修复Java中捕获转换的正确方法

Having a hierarchical model which uses inheritance and generics in collection, I have a compilation error related to capture conversion:

CaptureConversion.java:16: error: incompatible types: NodeModel cannot be converted to CAP#1
    treeModel.getNodes().set(0, primaryNode);
                                ^
  where CAP#1 is a fresh type-variable:
    CAP#1 extends PublicNodeModel from capture of ? extends PublicNodeModel

我能够克服此错误的唯一方法是通过以下转换方法:

private static <T extends PublicNodeModel> T convert(PublicNodeModel node) {
    return (T) node;
}

这种转换对我来说看起来很傻,所以我的问题是,是否存在某种“正确”的方式来处理Java中的这种转换?

The model and code causing this error is following (a full runnable example on GitHub).

简化模型(例如,没有吸气剂/设置剂等):

class PublicTreeModel {
    List<? extends PublicNodeModel> nodes = new ArrayList<>();
}

class TreeModel extends PublicTreeModel {}

class PublicNodeModel {}

class NodeModel extends PublicNodeModel {}

导致编译错误的用法:

TreeModel treeModel = Fixture.createModel();
int index = Fixture.indexOfPrimaryNode(treeModel.getNodes());
NodeModel primaryNode = (NodeModel) treeModel.getNodes().get(index);

// following two lines won't compile
treeModel.getNodes().set(index, treeModel.getNodes().get(0));
treeModel.getNodes().set(0, primaryNode);

Usage with aforementioned fix (the convert() method):

// this will compile & run
treeModel.getNodes().set(index, convert(treeModel.getNodes().get(0)));
treeModel.getNodes().set(0, convert(primaryNode));
评论