How can I return a list of a specific type when calling a generic method that takes a class <T> and returns T?

I am calling a method from a library with this signature:

public <T> T get(Class<T> c) 

And I would like to get List<MyClass> as return value. But a call of this type does not compile ("Unable to select from a parameterized type"):

 List<MyClass> myClasses = get(List<MyClass>.class); 

This compiles, but gives a warning:

 List<MyClass> myClasses = get(List.class); 

The warning says "Unverified job." How can I avoid this warning and not leave my list?

+6
source share
2 answers

Here you are using generics, so the base type of the item in the list was deleted at runtime, and the compiler knows that it cannot check it for you at compile time, thereby warning. If you use the generic type here, you cannot escape the warning. You can suppress it if you know for sure that your throw will not result in an exception.

 @SuppressWarnings("unchecked") 
+3
source

Note I post this as an interesting point rather than as a recommended answer. You generally better avoid warnings.

If you really hate to suppress warnings, but you also hate to see warnings, there is a hacker alternative to the accepted answer. You can create an archetype object, for example ArrayList<MyClass> , and then pass archetype.getClass() to the general method instead of List.class , as in the example and the accepted answer.

It will look like this:

 ArrayList<MyClass> archetype = new ArrayList<>(); List<MyClass> myClasses = get(archetype.getClass()); 

One obvious drawback here is the unnecessary cost of creating an archetype object, but this can be mitigated by making it a static instance. In my opinion, the big drawback is that you have to use a specific class as your archetype, which can be useless.

+1
source

Source: https://habr.com/ru/post/944921/


All Articles