实例化循环引用的泛型类

时间:2017-12-30 13:27:27

标签: java generics

有一种技巧可以在Java泛型中进行类间循环引用:

public static class GenA<A extends GenA<A, B>, B extends GenB<A, B>> {
    public B objB;
}
public static class GenB<A extends GenA<A, B>, B extends GenB<A, B>> {
    public A objA;
}

当我尝试实例化真实对象时:

GenA<GenA, GenB> genA = new GenA<>();

我收到编译错误:

CircularRef.java:7: error: type argument GenA is not within bounds of type-variable A
        GenA<GenA, GenB> genA = new GenA<>();
  where A,B are type-variables:
    A extends GenA<A,B> declared in class GenA
    B extends GenB<A,B> declared in class GenA
CircularRef.java:7: warning: [rawtypes] found raw type: GenA
        GenA<GenA, GenB> genA = new GenA<>();
  missing type arguments for generic class GenA<A,B>
  where A,B are type-variables:
    A extends GenA<A,B> declared in class GenA
    B extends GenB<A,B> declared in class GenA
CircularRef.java:7: warning: [rawtypes] found raw type: GenB
        GenA<GenA, GenB> genA = new GenA<>();
  missing type arguments for generic class GenB<A,B>
  where A,B are type-variables:
    A extends GenA<A,B> declared in class GenB
    B extends GenB<A,B> declared in class GenB
CircularRef.java:7: warning: [unchecked] unchecked method invocation: constructor <init> in class GenA is applied to given types
        GenA<GenA, GenB> genA = new GenA<>();
  required: no arguments
  found: no arguments
CircularRef.java:7: warning: [unchecked] unchecked conversion
        GenA<GenA, GenB> genA = new GenA<>();
  required: GenA<GenA,GenB>
  found:    GenA

我知道解决方法:

public static class AdapterA extends GenA<AdapterA, AdapterB> { } 
public static class AdapterB extends GenB<AdapterA, AdapterB> { } 

的作用如下:

AdapterA adA = new AdapterA();
AdapterB adB = new AdapterB();
adA.objB = adB;
adB.objA = adA;

如何直接实例化GenA / GenB类?

他们不是abstract。我喜欢-Xlint:all也没有警告。

EXTRA 我写了问题Defining typed hierarchy with Java generics and type self-referencing,其中包含隐藏在很多代码中的上述问题,无聊的用户喜欢关闭它))

关于声明通用循环引用声明的一些提示位于:

更新添加额外参考:

public static class GenA<A extends GenA<A, B, C>, B extends GenB<A, B, C>, C extends GenC<A, B, C>> {
    public B objB;
    public C objC;
}
public static class GenB<A extends GenA<A, B, C>, B extends GenB<A, B, C>, C extends GenC<A, B, C>> {
    public A objA;
    public C objC;
}
public static class GenC<A extends GenA<A, B, C>, B extends GenB<A, B, C>, C extends GenC<A, B, C>> {
    public A objA;
    public B objB;
}

问题同样如下:

GenA<GenA, GenB, GenC> genA = new GenA<>();

可以像往常一样解决:

public static class AdapterA extends GenA<AdapterA, AdapterB, AdapterC> { } 
public static class AdapterB extends GenB<AdapterA, AdapterB, AdapterC> { } 
public static class AdapterC extends GenC<AdapterA, AdapterB, AdapterC> { } 

更新2 问题不是实例化,而是声明类型,以下失败:

GenA<GenA, GenB> genA;

1 个答案:

答案 0 :(得分:2)

您可以在具有自己的类型变量的方法中实例化:

<A extends GenA<A, B>, B extends GenB<A, B>> GenA<A, B> thing() {
  return new GenA<>();
}

当然,这只是解决了&#34;我如何实例化它的问题&#34; to&#34;如何调用此方法&#34;。答案是在具有自己的类型变量的方法中调用它(或使用GenA<?, ?>作为接收值的类型。)