Higher-kinded generics in Java

后端 未结 5 936
别跟我提以往
别跟我提以往 2020-12-05 13:07

Suppose I have the following class:

public class FixExpr {
  Expr in;
}

Now I want to introduce a generic argument, abstract

5条回答
  •  天命终不由人
    2020-12-05 13:44

    I think what you're trying to do is simply not supported by Java generics. The simpler case of

    public class Foo {
        public T bar() { return null; }
    }
    

    also does not compile using javac.

    Since Java does not know at compile-time what T is, it can't guarantee that T is at all meaningful. For example if you created a Foo, bar would have the signature

    public BufferedImage bar()
    

    which is nonsensical. Since there is no mechanism to force you to only instantiate Foos with generic Ts, it refuses to compile.

提交回复
热议问题