A和AService是基类。
B和BService扩展了这些类。
A和B是包含服务参数的bean。
BService期望在execute方法中使用B类型的参数。
public class A
{
private int a1;
public int getA1() { return a1; }
public void setA1(int a1) { this.a1 = a1; }
}
public class B extends A
{
private int b1;
public int getB1() { return b1; }
public void setB1(int b1) { this.b1 = b1; }
}
public abstract class AService
{
public int execute(A a)
{
return a.getA1() + getValue();
}
public abstract int getValue(A a);
}
public class BService extends AService
{
public int getValue(A a)
{
B b = (A) a;
return b.getB1();
}
}
有没有更好的方法来执行此代码? 特别是,有没有办法避免投射物体?
答案 0 :(得分:1)
听起来generics正是您所寻找的。通常,只要有一个可以始终安全地转换值的具体类,通常可以通过泛型参数表达它(并在编译时检查它)。
在这个特定示例中,您将使用泛型参数声明AService
,该参数必须是某些 A的子类。然后,您使用该参数来创建特定于特定的某些方法type - 在这种情况下是getValue
方法,类似于
public class AService<T extends A> {
// Now this takes a T - i.e. the type that a subclass is parameterised on
public abstract int getValue(T a)
// Execute will have to take a T as well to pass into getValue - an A
// wouldn't work as it might not be the right type
public int execute(T a)
{
return a.getA1() + getValue(a);
}
}
其中T
是类型参数(通常是单个大写字母)。然后你可以将BService声明为
public class BService extends AService<B> {
// The type is checked by the compiler; anyone trying to pass an instance
// of A into this class would get a compile-time exception (not a class cast
// at runtime)
public int getValue(B b) {
return b.getB1();
}
}