Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with this java generic method syntax

Tags:

java

generics

I've 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 method call find(......) is failing at compile time with error message

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

This method has to return object of type List<KeyValue<Object>>.

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

Thank you.

like image 343
Arun P Johny Avatar asked May 13 '11 07:05

Arun P Johny


1 Answers

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

Either use two different 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 your find declaration or repair your call to find.

like image 63
BertNase Avatar answered Oct 17 '22 23:10

BertNase