Java编译器无法推断通用链上的类型 [英] Java compiler not able to infer type on generic chain

查看:66
本文介绍了Java编译器无法推断通用链上的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如下所述(为了说明这一点,我可能对此做过不好的解释):

As mentioned below (to remark it as I might have explained myself badly):

我想了解此问题的原理,以便将这些知识应用于实际问题.


问题开始

我正在一个旨在成为许多子系统使用的抽象库的系统中工作.想法是使标准行为可由实现扩展. 我的问题是Java编译器无法推断方法参数的类型,尽管它没有任何意义,因为在每个相关的通用类/方法上都已很好地设置了边界.

I am working in a system intended to be an abstract library to be used by many subsystems. The idea is to have an standard behaviour extensible by implementations. My problem is that java compiler is not able to inferr method parameter type, even though it makes no sense since the boundaries are well set on every related generic class/method.

下面有一个示例,是重现该问题的最小示例.我知道在此示例中它看起来有点愚蠢,但这是因为简化了:

Below there is an example, the minimum example to reproduce the problem. I am aware it looks a bit silly in this example, but that is because of the simplification:

    public class Test {
    public static void main(String[] args) {
        Gen<? extends Base> gen = new HijaGen();
        gen.applyTo(Hija.EXAMPLE);
    }
    private interface Base {
        String getName();
    }
    private enum Hija implements Base {
        EXAMPLE;
        @Override
        public String getName() {
            return this.name();
        }
    }
    private interface Gen<T extends Base> {
        boolean applyTo(T base);
    }
    private static class HijaGen implements Gen<Hija> {
        @Override
        public boolean applyTo(Hija base) {
            return false;
        }
    }
}

基本上,它说applyTo期望Base和Hija的子类无效,这在我看来是没有道理的.

Basically it says that applyTo expects a subclass of Base and Hija is not valid, which from my perspective makes no sense.

谢谢.

此代码用于库,因此解决方案无法指定类型,因为那样就无法通过特定的实现对其进行扩展.

This code is for a library, so that the solution could not be specifying the type since then it could not be extensible through particular implementations.

我已经知道,如果我指定泛型类型而不是抛出类型通配符,它​​将完全正常工作.但是我的问题是,即使Hija继承了Base的子类,而方法firm需要Base的子类,它也永远不会编译...

I am already aware that if I specify the generic type instead of throwing a type wildcard it will perfectly work. But my question is how is it possible that even though Hija subclasses Base, and method firm requires a subclass of Base it will never compile...

我想了解此问题的原理,以便将这些知识应用于实际问题.

I want to understand the principle behind this issue so that I can apply that knowledge to the real problem.

推荐答案

我认为docs

I think there is a similar problem explained in the docs here and the problem that they propose is to make a helper (or wrapper) to clarify the types. So I guess you can try adding this function:

private static <T extends Base> boolean applyTo(Gen<T> gen, T base){
    return gen.applyTo(base);
}

并如下更改主要功能:

public static void main(String[] args) {
    boolean b = applyTo(new HijaGen(), Hija.EXAMPLE);
}

这篇关于Java编译器无法推断通用链上的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆