使用反射将对象声明为自身

时间:2014-06-24 14:20:48

标签: java java-ee

不确定标题,但这里是:

我有一个将要扩展的课程,例如:

public class A{

    public void methodThatDoesStuff(){
        //Uses AA here
    }

    protected class AA{
        //does most of the stuff here
    }
}

public class B extends A{
    public class BB extends AA{
    }
}

如你所见。 methodThatDoesStuff使用AA,但是当调用B时,我希望它使用BB代替。

这样做的原因是AA有一些对所有类都很常见的变量。但有些不同。 innerClasses是具有@Expose变量,setter和getter的JSONObject。

我如何在超类中指定要使用哪个类?

2 个答案:

答案 0 :(得分:0)

您无法指定在超类中使用哪个类,因为超类没有从中继承的类的信息。在超类中定义类型AA的变量,并使用构造函数或setter在运行时设置适当的实例。示范:

public class A {
    protected AA serviceVar;

    public A() {
        this.serviceVar = new AA();
    }

    public void methodThatDoesStuff() {
        System.out.println(serviceVar);
    }

    protected class AA {
        protected String message;

        public AA() {
            message = "AA";
        }

        public String toString() {
            return message;
        }
    }
}

public class B extends A {
    public B() {
        this.serviceVar = new BB();
    }

    public class BB extends AA {
        public BB() {
            this.message = "BB";
        }
    }
}

public class Test {
    public static void main(String[] args) {
        A a = new A();
        A b = new B();
        a.methodThatDoesStuff();
        b.methodThatDoesStuff();
    }
}

正如您所看到的,当您实例化A时,方法methodThatDoesStuff会根据AA打印出消息,当您实例化B时,它会使用BB而是。您可以使用serviceVar分别需要AA或其中某些子类的功能。这意味着在您的情况下,您在methodThatDoesStuff

中使用此变量

答案 1 :(得分:0)

执行此操作的常用方法是定义用于创建AA对象的函数,子类可以覆盖该函数。这允许子类创建对象,如果需要,可以创建AA的子类。

public class A{

    public void methodThatDoesStuff(){
        AA aa = getAA();
        // use aa
    }

    protected class AA{
        //does most of the stuff here
    }

    // Function to create AA instances. Subclasses
    // can override this.
    protected AA getAA() {
        return new AA();
    }
}

public class B extends A{
    public class BB extends AA{
    }

    @Override
    protected AA getAA() {
       return new BB();
    }
}