服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

“javax.microedition.io.connecotr”研究

在研究在j2me发送短消息的时候,这段代码让我很困惑:
messageconnection smsconn = null;
try {
  /** open the message connection. */
  smsconn = (messageconnection)connector.open(address);

  textmessage txtmessage = (textmessage)smsconn.newmessage(messageconnection.text_message);
  txtmessage.setaddress(address);
  txtmessage.setpayloadtext(messagebox.getstring());
  smsconn.send(txtmessage);
} catch (throwable t) {
  system.out.println("send caught: ");
  t.printstacktrace();
}

1。messageconnection明明只是一个没有实现的接口类,能够取得它的实例并调用它的方法吗?如果能,它调用的方法体究竟在什么地方?
2。connector是根据什么来生成一个messageconnection类的?
决定自己来研究一下以上两个问题。

第一步 写了两个类来测试
public interface interfacea {
  public abstract void methoda();
}
public class classa {
  public interfacea methoda(){
    return new interfacea();
  }
}

程序报错,说interfacea是抽象的,不能实例化。这说明不能直接在classa中实现interfacea的实例,那么connector是怎么返回一个messageconnection对象的呢?

第二步 对classa代码做了如下修改
public class classa {
  class classb implements interfacea{
    public void methoda(){
    }
  }

  public interfacea methoda(){
    return new classb();
  }

  public void methodb(){
    interfacea ia = methoda();
    ia.methoda();
  }
}

哈,编译通过,搞定!原来在classa内部或者其它地方实现了interfacea接口,这个classa作为一个工厂类,由它构造了一个interfacea的实现。那么,现在我来看看connector内部是不是这么实现的。

第三步 connector类分析
从connector类的工厂方法实现中(openprim)找到如下代码:
 
int colon;
  if(name == null)
    throw new illegalargumentexception("null url");
  colon = name.indexof(58);
  if(colon < 1)
    throw new illegalargumentexception("no ':' in url");
  connectionbaseinterface uc;
  string protocol = name.substring(0, colon);
  name = name.substring(colon + 1);
  class clazz = class.forname(classroot + "." + platform + "." +
                              protocol + ".protocol");

connector根据传入参数中的url协议部分来生成相应的类!和我的设想相同:)

本人看来,这种实现方式的好处就在于“隐藏实现”。

扫描关注微信公众号