Johan Sjöberg
Johan Sjöberg

Reputation: 43

Java generic cast by parameter type

what, if at all possible, would be a good solution to implement the following desired functionality where I want to:


// 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);

Upvotes: 4

Views: 2941

Answers (1)

John Kugelman
John Kugelman

Reputation: 361635

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

Upvotes: 5

Related Questions