简体   繁体   English

Java方法返回的类的泛型类型

[英]Java method returning type of generic type of generic used at class

This is simple structure of code i wanna realize: 这是我想要实现的简单代码结构:

public class B {}
public class A<X extends B> {
    X x;
    public A(X x) {this.x = x;}
    public X getX() {return x;}
}
public class C<A> {
    public A getA() {return null;}       
    public A<T> T getGenericXOfA() {return getA().getX();}
}

I wanna to my class C by using method 'getGenericXOfA' returns type used at generic parameter of class A. Is that even possible at Java? 我想通过使用方法'getGenericXOfA'返回我的类C,该返回类型用于类A的泛型参数。在Java上甚至可能吗? I wanna do something like that: 我想做这样的事情:

public class C<A<X>> {
    public A getA() {return null;}       
    public X getGenericXOfA() {return getA().getX();}
}

or like that?: 还是那样?:

public class C<A> {
    public A getA() {return null;}       
    public A<T> T getGenericXOfA() {return getA().getX();}
}

You used a raw type of the A when you need to generalise it by X which extends B : 当需要通过扩展BX进行归纳时,可以使用A的原始类型:

class C<X extends B> {

    public A<X> getA() { ... }

    public X getGenericXOfA() {
        return getA().getX();
    }

}

Actually, you are playing with names of generic parameters. 实际上,您正在使用通用参数的名称。 They don't matter and can't refer to existing classes. 它们没有关系,也不能引用现有的类。

If you want the same generic type like another class has, you should repeat the same template. 如果您希望像其他类一样具有相同的泛型类型,则应重复相同的模板。

You can do: 你可以做:

public class C<X extends B, Y extends A<X>> {
    public Y getA() {return ... }       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM