Java中的高级泛型
假设我有以下课程:
public class FixExpr {
Expr<FixExpr> in;
}
现在我想介绍一个通用参数,对 Expr 的使用进行抽象:
Now I want to introduce a generic argument, abstracting over the use of Expr:
public class Fix<F> {
F<Fix<F>> in;
}
但 Eclipse 不喜欢这样:
But Eclipse doesn't like this:
类型 F 不是泛型的;它不能用参数 <Fix<F>>
The type F is not generic; it cannot be parametrized with arguments <Fix<F>>
这是否可能,或者我是否忽略了导致此特定实例中断的某些内容?
Is this possible at all or have I overlooked something that causes this specific instance to break?
一些背景信息:在 Haskell 中,这是编写泛型函数的常用方法;我正在尝试将其移植到 Java.上例中的类型参数 F 具有种类 * -> * 而不是通常的种类 *.在 Haskell 中它看起来像这样:
Some background information: in Haskell this is a common way to write generic functions; I'm trying to port this to Java. The type argument F in the example above has kind * -> * instead of the usual kind *. In Haskell it looks like this:
newtype Fix f = In { out :: f (Fix f) }
推荐答案
我认为 Java 泛型根本不支持您尝试做的事情.更简单的情况
I think what you're trying to do is simply not supported by Java generics. The simpler case of
public class Foo<T> {
public T<String> bar() { return null; }
}
也不使用 javac 编译.
also does not compile using javac.
由于Java 在编译时不知道T
是什么,它不能保证T
是有意义的.例如,如果您创建了一个 Foo
,则 bar
将具有签名
Since Java does not know at compile-time what T
is, it can't guarantee that T<String>
is at all meaningful. For example if you created a Foo<BufferedImage>
, bar
would have the signature
public BufferedImage<String> bar()
这是荒谬的.由于没有机制强制你只用通用 T
s 实例化 Foo
s,它拒绝编译.
which is nonsensical. Since there is no mechanism to force you to only instantiate Foo
s with generic T
s, it refuses to compile.
相关文章