ArkadiuszK
ArkadiuszK

Reputation: 23

Class type as a parameter in Java

I have a method:

private List<ApplicationForVacancy> createListOfApplicationsForVacancy(List<Document> documents) {
        return documents.stream()
                .filter(d -> d instanceof ApplicationForVacancy)
                .map(d -> (ApplicationForVacancy) d)
                .collect(Collectors.toList());
}

but I'd like to pass the name of the class/the type of the class in parameter and return type of the method like this:

private List<TypeOfSomeClass> createList (List<Document> documents, String or Type typeOfSomeClass) {
            return documents.stream()
                    .filter(d -> d instanceof typeOfSomeClass)
                    .map(d -> (typeOfSomeClass) d)
                    .collect(Collectors.toList());
}

Is it possible? How can I do that?

Upvotes: 2

Views: 89

Answers (2)

Basti
Basti

Reputation: 1186

To my knowledge you can't perform a type conversion like this. But you could create a new List instance at the start of your method, containing the specified type. Then loop through your existing list, filtering out all instances that should be contained in the result. Add those, then return the new List. Here some pseudo code.

public <T> List<T> filterInstances(List<?> input, Class<T> type){
  List<T> result = new ArrayList<>();
  for(Object o : input){
    if(type.isAssignableFrom(o.getClass()){
      result.add((T)o);
    }
  }
  return result;
}

Upvotes: 0

Joachim Sauer
Joachim Sauer

Reputation: 308269

You have to provide a Class object to declare the type and add a type parameter to the method, like this:

private static <T> List<T> filterType(List<?> input, Class<T> clazz) {
    return input.stream()
            .filter(clazz::isInstance)
            .map(clazz::cast)
            .collect(Collectors.toList());
}

You then call the method like this:

List<Object> stuff = List.of("String", Integer.valueOf(3), Double.valueOf(42), new Object());
List<String> strings = filterType(stuff, String.class);
List<Number> numbers  = filterType(stuff, Number.class);

strings will only contain String and numbers will contain the 2 numeric values.

Upvotes: 6

Related Questions