Saturday, March 12, 2011

对象初始化顺序导致的问题

废话少说,直接上代码。
public abstract class Container{
 private Map<Integer,Integer> maps = new HashMap<Integer,Integer>();
 private final int position;
 private final int status;
 public Container(int pos,int status){
    this.position = pos;
    this.status = status;
    load();
 }
 protected void load(){
  maps.put(1,1);
  ...
 }
}

public class Stall extends Container{
 private Map<Integer,Integer> itemMoneys = new HashMap<Integer,Integer>();
 public Stall(int pos){
  super(pos,Constants.STALL);
 }
 @Override
 protected void load(){
   itemMoneys.put(1,1000);
   ...
 }
}
调用类:
Stall stall = new Stall(100);

//红色处抛出NullPointException异常,一开始总是想不明白是什么问题,后来跟同事讨论,同事给出正确问题,因为在Stall构造方法调用了super的构造方法,而构造方法里调用了load方法,子类重写了load方法,而此时子类还没有初始化完,也就是说itemMoneys还没初始化,所以才会抛出异常。

Friday, March 11, 2011

Netty 3.2.1 API中文版初稿

终于花了2个月的时间基本翻译完了Netty的API,还差几个codec包没完成,先把完成的放出了,翻译的不好的请大家指出完善。