避免对Java中的数据类进行继承的动态类型转换

我有3个数据类

.

B和C类之间有一些公共字段,它们保留在其父类A中。 以下是测试人员课程

@Data
class A
{
    private int a;
}

@Data
class B extends A
{
    private int b;
}

@Data
class C extends A
{
    private int c;
}

现在我看到的问题是不安全的动态类型转换,它可能会遇到类转换问题。一种可能的解决方案是在B类和C类中分别创建单独的数据对象并为两个对象设置公共字段(对于我的实际情况而言太多),然后将如下所示:

class TesterClass
{
    static String bOrC = "C"; // input from some decision
    public static void main(String[] args) // assume this to be the client
    {
        A a;
        if (bOrC.equals("B")) {
            B b = new B();
            b.setB(11);
            a = b;
        } else {
            C c = new C();
            c.setC(12);
            a = c;
        }
        a.seta(10);
        doSomething(bOrC,a);

    }

    // Below are the service methods
    // only this method in the service exposed
    public static void doSomething(String bOrC,A a) {
        if (bOrC.equals("B")) {
            doSomethingWithB(a);
        } else if (bOrC.equals("C")) {
            doSomethingWithC(a);
        }
    }

    public static void doSomethingWithB(A a) {
        B b = (B) a; // possible ClassCastException
        System.out.println(b.geta());
        System.out.println(b.getB());
    }

    public static void doSomethingWithC(A a) {
        C c = (C) a; // possible ClassCastException
        System.out.println(c.geta());
        System.out.println(c.getc());
    }
}

我正在寻找一种避免这种动态类型转换的方法,但同时又避免了必须重复公用变量。谁能提出解决方案?

pingkang 回答:避免对Java中的数据类进行继承的动态类型转换

抽象是您要解释的行为的一种解决方案。在类A中创建一个抽象方法doSomething(...),并分别在子类B和C中实现它。这样,您就不需要静态方法,并且处理将基于B或C对象本身的实例进行。

    @Data
    class A
    {
        private int a;
        public abstract void doSomething();

    }

    @Data
    class B extends A
    {
        private int b;
        public void doSomething(){
/*.... do something here
* here you can also access parent public methods and properties.
* as you have already annotated with @Data you will have access to getA() method,* hence you can also use parent properties.
*/
        }
    }

    @Data
    class C extends A
    {
        private int c;
        public void doSomething(){
        /*.... do something here
        * here you can also access parent public methods and properties.
        * as you have already annotated with @Data you will have access to 
        * getA()         method,* hence you can also use parent properties.
        */

    }

现在您可以按以下方式使用它

   public static void main(Strings[] args){
       A a;
       B b = new B();
       b.setB(10);
       b.doSomething();

       C c = new C();
       c.setC(30);
       c.doSomething();
   }
本文链接:https://www.f2er.com/2443555.html

大家都在问