What's wrong with this java generic method syntax

I have the following classes

KeyValue.java

package test; public class KeyValue<T> { private String key; private T value; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public T getValue() { return value; } public void setValue(T value) { this.value = value; } } 

Reader.java

 package test; public interface Reader<T> { <S extends T> S read(Class<S> clazz); } 

Test.java

 package test; import java.util.List; public class Test { public static void main(String[] args) { List<KeyValue<Object>> list = find(KeyValue.class, new Reader<KeyValue<Object>>() { @Override public <S extends KeyValue<Object>> S read(Class<S> clazz) { return null; } }); } public static <T> List<T> find(Class<T> targetClass, Reader<T> reader) { return null; } } 

Here the call to the find(......) method find(......) does not work at compile time with an error message

The find (Class, Reader) method in the Test type is not applicable for arguments (Class, new Reader> () {}).

This method should return an object of type List<KeyValue<Object>> .

What is wrong with this design and how to fix it.

Thanks.

+6
source share
3 answers

find defines T and T (in the first and second argument) of the same type - your call to find uses the Object type in the first arg and the Type KeyValue<Object> in the second arg.

Use either two type identifiers (e.g. T and X, i.e. public static <T, X extends T> List<T> find(Class<T> targetClass, List<X> reader) ) in the find declaration, or restore its call to find .

+2
source

you want to get a list of your KeyValue class from your find method but u defined it as a list note that this is a list T not KeyValue change the ur method declaration as follows

 private static <T> List<KeyValue<T> > find(Class<KeyValue> aClass, Reader<KeyValue<T> > reader) { throw new UnsupportedOperationException("Not yet implemented"); } 

I think this is what you want

+1
source

Try declaring Test as

public class Test<T> { .

-1
source

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


All Articles