从外部Jar转发实例

时间:2015-03-04 12:26:39

标签: java downcast

//Class defined in external jar
class A{
    many methods...
    public getId() {};
}

//I want to extends this class and overwrite single method
class MyA extends A{
private int myId;
public getId() {return myId};
}

void main ()
{
  A a = Factory.getA(); //External class create the instance
  MyA mya = (MyA)a;     //runtime Error!! I want to convert A to myA
}

您好, 我想扩展一个从外部Jar获取的实例并覆盖单个方法getId()。我不控制实例的创建,所以我得到的唯一解决方案是将它传递给我的构造函数并手动初始化所​​有成员,例如:

class MyA extends A{
private int myId;
public MyA(A a, int myId)
{
    this.myId = myId;
    //init all other methods from a.? to this.?
    this.setXXX(a.getXXX());
    this.setYYY(a.getYYY());
    ....many methods...
}
public getId() {return myId};
}

有更好的方法吗?

2 个答案:

答案 0 :(得分:0)

MyA mya =(MyA)a; //运行时错误!!我想将A转换为myA 是一个instance of MyA ??如果它不是instance of MyA,则无法转换。你得到java.lang.ClassCastException

答案 1 :(得分:0)

而不是从A的构造函数中获取MyA的所有数据(从而完全重新实现),创建一个Adapter,更改所需的方法,其余的只是通过调用A的原始实例:

class MyA extends A{
private A adaptee;
private int myId;

public MyA(A adaptee, int myId)
{
    this.adaptee = adaptee;
    this.myId = myId;
}

// Override the method you need to 
@Override
public getId() {return myId};
...
// Override the rest of the methods so they call the adaptee.
@Override
public X getXXX() {
   return a.getXXX();
}
@Override
public void setXXX(X x) {
   a.setXXX(x);
}
...
}

然后,当然,请将其用作:

 A a = new MyA(Factory.getA(), myId);
... a.getId();