Java 执行此代码的更好方法
A和A服务是基类 B和B服务扩展了这些类 A和B是包含服务参数的bean BService要求execute方法中有一个B类型的参数Java 执行此代码的更好方法,java,generics,Java,Generics,A和A服务是基类 B和B服务扩展了这些类 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; publ
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();
}
}
有没有更好的方法来执行此代码?
特别是,有没有避免投射对象的方法?听起来像是你在寻找的。通常,当您有一个始终可以安全地强制转换值的具体类时,您通常可以通过泛型参数来表示(并在编译时检查)
在这个特定的示例中,您将使用一个泛型参数来声明AService
,该参数必须是a的某个子类。然后使用该参数来创建特定于特定类型的一些方法—在本例中是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);
}
}
在哪里投射对象?你的问题是什么?你试了什么?结果是什么?抽象方法没有指定body@Balaswamy瓦德曼:复制/粘贴错误,已编辑。@Tichodroma:代码中只有一个cast,在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();
}
}