泛型类型内部参数

时间:2014-09-29 12:33:27

标签: java generics

我有以下内容:

public <T extends Node> T create(Class<T> classType, String id, Transaction t){
    T obj;
    try {
        NodeKey nodeKey = new NodeKey(classType, id);
        obj = classType.getConstructor(NodeKey.class, Transaction.class).newInstance(nodeKey, t);
        add(obj, t);
        return obj;
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

你可以看到,我“建立”NodeKey nodeKey = new NodeKey(classType, id);;我希望能够重载只接受NodeKeyTransaction的上述方法,但是我不知道如何告诉泛型,T类型是类似{等方法返回的类{1}}。

这可能吗?

1 个答案:

答案 0 :(得分:1)

如果NodeKey本身没有参数化,那么它的任何方法都无法明确命名该类型。你必须使用不安全的演员表来找到解决方法。