Return generic type from generic function

we have a method more or less similar to the following. however, we are currently returning a List which, in the bla () function, will return List<Bar>at runtime.

I am looking for a way to do both

List<Interface> =  troubleFuction(foo, bar.getCLass());;

and

List<Bar> = troubleFuction(foo, bar.getCLass());;

perhaps. basicaly I want it to return a List that is compatible with the interface however this gives the following error:

* Type mismatch: cannot convert from List<capture#3-of ? extends Bar>toList<Interface>*

is there a way to make this type of return value possible or erasing at runtime makes it impossible

public <T1 extends Interface, T2 extends Interface> List<"problem"> troubleFunction( T1 in, Class<T2> clazz) {
  return in.doStuffWhichGeneratesAlistOF(clazz)
}

public void bla() {
  Foo foo = new Foo(); // implements interface
  Bar bar = new Bar(); // implements interface
  List<Interface> ifaces = toubleFuction(foo, bar.getCLass());
  List<Bar> mustAlsoWork = toubleFuction(foo, bar.getCLass());
}

edit: in a variety of existing codebases, a method is called as

List<Bar> result = troubleFunction(List<Interface> list, Bar.class);

thus, this type of return should remain compatible (rewriting / refactoring is not an option)

Essentially, I want the method to return a List <? super Bar>if it was called as

troublefunction(foo, Bar.class);

List<? super Foo>

troublefunction(foo, Bar.class);
+3
4

, ( ), .

, , troubleFunction return List<T2>? , , List<? extends Interface>.

+1

, , . , doStuffWhichGeneratesAlistOF() , . , "in" .

, , . ,

public <T extends Interface> List<T> troubleFunction(Interface in, Class<? extends T> clazz) {
  List<T> result = new ArrayList<T>();
  result.add(clazz.newInstance());
  return result;
}

, ( , ):

List<Interface> iface = this.troubleFunction(foo, bar.getCLass());

, , in.doStuffWhichGeneratesAlistOF(clazz), , , . , .

+1

, , . , , , , , :

List<Interface> iface = this.<Interface>troubleFunction(foo, bar.getCLass());

public <T extends Interface> List<T> troubleFunction(
    T in, Class<? extends T> clazz
) {
0

I looked at this again, and the problem was that I wanted to use the “super” type of return the signature I was looking for was more or less:

 public <T1 extends interface, T2 super T1> List<T2> getAList(Class<T1> clazz); 

which is impossible

0
source

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


All Articles