2014-09-29 53 views
0

泛型类型,我有以下几点:内部参数

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型是由像nodeKey.getUserType()方法返回的类。

这可能吗?

+0

你想添加一个通用参数到'NodeKey'吗?因此,'NodeKey nodeKey = new NodeKey (classType,id);'。 (和以前一样,我建议避免反射。) – 2014-09-29 12:40:16

回答

1

如果NodeKey本身没有参数化,它的任何方法都不可能明确指定类型。你必须使用不安全的强制转换来找到解决方法。

+0

你是对的,我可以参数化NodeKey! 如果您使用NodeKey的快速示例进行编辑,我会接受您的答案 – Lesto 2014-09-29 12:42:49