我有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());
}
}
我正在寻找一种避免这种动态类型转换的方法,但同时又避免了必须重复公用变量。谁能提出解决方案?