简体   繁体   English

这个java泛型方法语法有什么问题

[英]What is wrong with this java generic method syntax

I've the following classes 我有以下课程

KeyValue.java 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 Reader.java

package test;

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

Test.java 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 这里方法调用find(......)在编译时失败并显示错误消息

The method find(Class, Reader) in the type Test is not applicable for the arguments (Class, new Reader>(){}). Test类型中的find(Class,Reader)方法不适用于参数(Class,new Reader>(){})。

This method has to return object of type List<KeyValue<Object>> . 此方法必须返回List<KeyValue<Object>>类型的List<KeyValue<Object>>

What is wrong with this design and how to fix this. 这个设计有什么问题以及如何解决这个问题。

Thank you. 谢谢。

find defines 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. find将T和T(在第一个和第二个arg中)定义为相同的类型 - 您对find的调用在第一个arg中使用Object类型,在第二个arg中使用Type KeyValue<Object>

Either use two different type identifiers (eg T and X, ie 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 . 在您的find声明中使用两个不同的类型标识符(例如T和X,即public static <T, X extends T> List<T> find(Class<T> targetClass, List<X> reader) )或修复您的调用find

you want to get a list of your class KeyValue from your method find but u defined it as List note that it is a list of T not KeyValue change ur method declaration to be as follows 你想从你的方法中找到你的类KeyValue的列表,但是你把它定义为List注意它是一个T的列表而不是KeyValue的改变方法声明如下

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 u want 我想这就是你想要的

Try to declare Test as 尝试将Test声明为

public class Test<T> { . public class Test<T> {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM