简体   繁体   中英

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? 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 :

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 ... }       
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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