Reputation: 877
I have a List
containing objects of different subclasses. Now I want to get all of a specific subclass. So I tried to write a generic getter method. My approach is obviously wrong, as I get compile errors because of the T
.
public List<T extends Resource> getAllInstancesOfType(T) {
List<T> resources = new ArrayList<>();
for (Resource resource : resources) {
if (resource instanceof T)
resources.add((T) resource);
}
return resources;
}
Upvotes: 0
Views: 525
Reputation: 37655
Because generic information is erased, you cannot use instanceof
with a type parameter. Instead you need a Class
object.
public <T extends Resource> List<T> getAllInstancesOfType(Class<T> clazz) {
List<T> resources = new ArrayList<>();
for (Resource resource : otherResources) {
if (clazz.isInstance(resource))
resources.add((T) resource);
}
return resources;
}
You can use this by passing SomeResourceType.class
.
Upvotes: 2
Reputation: 2153
Here is a method to which you can pass the list and the Class that you want to get from the list
public <T extends Resource, S extends Resource> List<S> getAllInstancesOfType(List<T> resources, Class<S> clazz) {
List<S> subResources = new ArrayList<S>();
for (Resource resource : resources) {
if (clazz.isAssignableFrom(resource.getClass()))
subResources.add((S)resource);
}
return subResources;
}
And here is how to use this method
System.out.println(getAllInstancesOfType(Arrays.asList(new Resource(), new Course(), new Course()), Course.class));
Upvotes: 1
Reputation: 8387
This is the syntax.
public <T extends Resource> List<T> magicalListGetter(Class<T> type) {
...
return list;
}
or like this same to your code, should give a name of param T in input.
public <T extends Resource> List<T> magicalListGetter(T t) {
...
return list;
}
Upvotes: -1