Java泛型:非法的前向引用 [英] Java generics: Illegal forward reference

查看:313
本文介绍了Java泛型:非法的前向引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个通用接口

  interface Foo< A,B> {} 

我想编写一个需要A成为B的子类的实现。要做

  class Bar  //  - >语法错误

  class Bar< A extends B,B>实施Foo< A,B> {} 
// - >非法前向引用

但是唯一可行的解​​决方案是这样的:

  class Bar< B,A extends B>实施Foo< A,B> {} 

这很丑陋,因为它颠倒了泛型参数的顺序。

是否有任何解决方法或解决方法解决此问题?

解决方案

,试着考虑 Bar



一个用于 Bar 的变量,首先指定父类,然后指定子类。这就是 Bar 的工作原理。不要认为它是倒退 - 认为它是前锋。父母自然应该在孩子面前指定。您添加的这种附加关系是驱动参数顺序的原因,而不是基础接口。


Given a generic interface

interface Foo<A, B> { }

I want to write an implementation that requires A to be a subclass of B. So I want to do

class Bar<A, B super A> implements Foo<A, B> { }
// --> Syntax error

or

class Bar<A extends B, B> implements Foo<A, B> { }
// --> illegal forward reference

But the only solution that seems to work is this:

class Bar<B, A extends B> implements Foo<A, B> { }

which is kind of ugly, because it reverses the order of the generic parameters.
Are there any solutions or workarounds to this problem?

解决方案

Since this isn't possible in Java, try to think of Bar<B, A extends B> differently.

When you declare a variable for Bar, you're specifying the parent class first and then the child class. That's how Bar works. Don't think of it as being backwards - think of it as being forwards. The parent should naturally be specified before the child. This additional relationship you added is what drives the parameter order, not the underlying interface.

这篇关于Java泛型:非法的前向引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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