功能接口中的通用参数是否有任何解决方法?

Is there any workaround for a generic argument in a functional interface?

我试图通过在基础组件 class 中为每种类型(更新、提取)创建一个方法来缩短我的数据库访问代码。 为此,我需要以某种方式存储 getter 和 setter,以便在需要时将它们附加到查询中——并且不使用反射。 所以我带来了这个:

class Component{
    protected final HashMap<String, Pair<Getter,Setter>> FIELDS = new HashMap<>();
    public void updateInDB(){
        // create update query, iterating through FIELDS (getters)
    }
}


public class TestComponent extends Component {

    private String color1;

    protected TestComponent(String user_id) {
        super(user_id);
        FIELDS.put("color1", new Pair<>(this::getColor1, this::setColor1));
    }

    public String getColor1() {
        return color1;
    }

    public void setColor1(String color1) {
        this.color1 = color1;
    }
}

Getter 看起来像这样:

public interface Getter<T> {
    T get();
}

Setter:

public interface Setter<T> {
    void set(T value);
}

一对class:

public class Pair<A, B> {

    private A first = null;
    private B second = null;

    public Pair(A first, B second) {
        this.first = first;
        this.second = second;
    }

    public A getFirst() {
        return first;
    }

    public void setFirst(A first) {
        this.first = first;
    }

    public B getSecond() {
        return second;
    }

    public void setSecond(B second) {
        this.second = second;
    }

}

错误是:B不是函数式接口,也就是说Setter接口不是函数式接口。对此有任何可能的解决方法吗?

让我们看看你的Pair<Getter,Setter>。因为你还没有参数化你的setter,它期望接口方法出现如下:

void set (Object value);

但这不是 setColor1 的意思。它需要 String,而不仅仅是任何旧的 Object

现在为了编译它,您需要将类型参数添加到 Setter:

protected final HashMap<String, Pair<Getter<String>,Setter<String>>> FIELDS = new HashMap<>();