0

I want to filter a list by a generic type. I have the resource of which I want to extract all elements of the generic type T like so:

class ListFilter<T> {
    Resource resource;
    ArrayList<T> filteredElements

    public ListFilter(Resource resource) {
        this.resource = resource;
        TreeIterator<EObject> it = resource.getAllContents();
        filteredElements = new ArrayList<>();
        while(it.hasNext()) {
            EObject nextElement = it.next();
            if (nextElement instanceof T) {  //This is where the error occurs
                elements.add((T) nextElement);
            }
        }
    }
}

I get the following error on the commented line:

Cannot perform instanceof check against type parameter T. Use its erasure Object instead since further generic type information will be erased at runtime

How can I filter resources by the generic type T and save the elements into the filteredElements list? I prefer a solution without the use of other libraries.

landunder
  • 342
  • 1
  • 4
  • 17

0 Answers0