设置<T> Class变量并接收Class实例

时间:2019-09-12 08:13:16

标签: java generics

我有PageA和PageB类。
方法和变量完全不同。
但是对于它们两者来说,从PageA和PageB的共同点是,应该可以调用Popup类的方法。

问题在于,在执行类Popup的方法“ closePopup”之后,它应该返回该类的实例,该实例称为他(PageA或PageB)。

我已经完成以下操作:

class PageA{

    public PageA dosomethingA(){
        //some code
        return this;
    }

    public Popup openPopup(){
        $("button.media").click();
        return new Popup(PageA.class);
    }
}

class PageB{

    public PageB dosomethingB(){
        //some code
        return this;
    }

    public Popup openPopup(){
        $("p.images").click();
        return new Popup(PageB.class);
    }
}


class Popup<T>{

    private Class<T> callerClass;

    public Popup(Class<T> callerClass) {
        this.callerClass = callerClass;
    }

    public Popup doSomething1(){
        //some code
        return this;
    }

    public Popup doSomething2(){
        //some code
        return this;
    }   

    public Popup doSomething3(){
        //some code
        return this;
    }   


    public Class<T> closePopup(){
        //some code
        return callerClass;
    }   
}

运行:

pageA.dosomethingA()
    .openPopup()
    .doSomething1()
    .closePopup()

    //Error Object class is returned, PageA class should be returned
    .dosomethingA();

pageB.dosomethingB()
    .openPopup()
    .doSomething2()
    .doSomething3()         
    .closePopup()   


    //Error Object class is returned, PageB class should be returned
    .dosomethingB();

问题是closePopup方法返回一个Object。 如何解决?

1 个答案:

答案 0 :(得分:2)

您有几个问题:

  1. 您的某些方法返回的是原始Popup而不是Popup<T>
  2. 您正在Class<T>中存储T实例而不是Popup<T>实例,因此您无法检索T

存储Class<T>而不是存储T

class PageA {

    public PageA dosomethingA(){
        //some code
        return this;
    }

    public Popup<PageA> openPopup(){

        return new Popup<PageA>(this);
    }
}

class Popup<T> {

    private T caller;

    public Popup(T caller) {
        this.caller = caller;
    }

    public Popup<T> doSomething1(){
        //some code
        return this;
    }

    public Popup<T> doSomething2(){
        //some code
        return this;
    }   

    public Popup<T> doSomething3(){
        //some code
        return this;
    }   


    public T closePopup(){
        //some code
        return caller;
    }   
}

现在以下各项将起作用:

PageA pageA = new PageA ();
pageA.dosomethingA()
     .openPopup()
     .doSomething1()
     .closePopup()
     .dosomethingA();