由参数类型转换的Java泛型

时间:2010-08-09 12:56:42

标签: java generics parameters casting

如果可能的话,在我想要的地方实现以下所需的功能将是一个很好的解决方案:

  • 将例程的返回类型转换为例程参数的类型,例如

// Foo and Bar are two types of Common
interface Common{}
interface Foo extends Common {}
interface Bar extends Common {}

// Example interface
public List<? extends Common> getFeatureByType(Class<? extends Common> clazz);


// Example of what I want to achieve by using the (or a similar) interface. 
// Can this be achieve without using typecasting to (List<Bar>) or (List<Foo>) 
// and @SuppressWarning("unchecked") ?
List<Bar> bars = getFeatureByType(Bar.class);
List<Foo> foos = getFeatureByType(Foo.class);

1 个答案:

答案 0 :(得分:5)

public <T extends Common> List<T> getFeatureByType(Class<T> clazz);