用泛型和接口实现一个组合

时间:2017-03-05 14:22:20

标签: java generics composition

我正在努力实现以下目标:

我的类X有一个通用的Y.然而,这个泛型Y需要访问X的资源,我想通过接口来处理它,以便允许其他人继承任意选择的类。

然而,我目前的方法导致了一系列泛型:

public class Goal<x X<y (this class)> implements Y {

    private final x minix;

    public Goal(x minix) {
        this.minix = minix;
    } 

    @Override
    public doSomething() {
        x.getO();
    }
}

我想要实现的目标:

public static final void main(String args[]) {
     String providerName = "192.168.10.60";

           String login = "sajjad";

           String passwd = "sajjad";

                String providerString = providerName + ";login=" + login + ";passwd=" + passwd;

/*
 * Create a provider by first obtaining the default implementation of
 * JTAPI and then the default provider of that implementation.
 */
Provider myprovider = null;
try {
  JtapiPeer peer = JtapiPeerFactory.getJtapiPeer(null);
  myprovider = peer.getProvider(providerString);
} catch (Exception excp) {
  System.out.println("Can't get Provider: " + excp.toString());
  System.exit(0);
}
System.out.println("Provider: " + myprovider.toString());

Address origaddr = null;
Terminal origterm = null;
try {
  origaddr = myprovider.getAddress("101");
  System.out.println(origaddr.getName());

  /* Just get some Terminal on this Address */
  Terminal[] terminals = origaddr.getTerminals();
  if (terminals == null) {
    System.out.println("No Terminals on Address.");
    System.exit(0);
  }  
  origterm = terminals[0];
  System.out.println("terminal " + java.util.Arrays.toString(terminals));
} catch (Exception excp) {
   System.out.println("No Terminals " + excp.toString());
}


  /*
 * Create the telephone call object and add an observer.
 */
Call mycall = null;
try {
  mycall = myprovider.createCall();
  System.out.println("my call " + mycall);
  mycall.addObserver(new MyOutCallObserver());

} catch (Exception excp) {
  System.out.println("No call " + excp.toString());
}

try {
    //here is the exception
   Connection c[] = mycall.connect(origterm, origaddr, "105");


} catch (Exception excp) {

    System.out.println("No calling " + excp.toString());
} 

如果没有使用抽象类的常用方法和组合的构造函数实现,我如何实现我的目标?

1 个答案:

答案 0 :(得分:1)

接口的泛型类型参数相互依赖。要解决递归问题,必须为每个接口引入第二个类型参数:

interface X<A extends Y<A, B>, B extends X<A, B>> {

    A getY(); //example    
    Object getO();

}

interface Y<A extends Y<A, B>, B extends X<A, B>> {

    B getX(); //example  
    void doSomething();

}

目标等级:

public class Goal<B extends X<Goal<B>, B>> implements Y<Goal<B>, B> {

    private final B minix;

    public Goal(B minix) {
        this.minix = minix;
    } 

    @Override
    public B getX() {
        return minix;
    }

    @Override
    public void doSomething() {
        minix.getO();       
    }

}