0

我的来源:

private static HashMap<String, Class<?>> mapLogic = new HashMap<String,Class<?>>();

mapLogic.put("s", Packet1.class);
mapLogic.put("a", Packet2.class);

public abstract class Packet { 
    public abstract void get(ChannelBuffer buffer);
    public abstract void send(ChannelBuffer buffer);
}

public class Packet1 extends Packet{

    @Override
    public void get(ChannelBuffer buffer) {
    }


    @Override
    public void send(ChannelBuffer buffer) {
    }

}


public class Packet2 extends Packet{

    @Override
    public void get(ChannelBuffer buffer) {
    }

    @Override
    public void send(ChannelBuffer buffer) {
    }

}

mapLogic.get("s").newInstance().get() <--- 获取或发送不可用

我怎样才能得到这些方法?

4

1 回答 1

3

改变这个:

private static HashMap<String, Class<?>> mapLogic = new HashMap<String,Class<?>>();

对此:

private static HashMap<String, Class<? extends Packet>> mapLogic =
    new HashMap<String, Class<? extends Packet>>();

这样表达式mapLogic.get("s")就有了 type Class<? extends Packet>,而表达式mapLogic.get("s").newInstance()就有了 type Packet

你现在拥有它的方式,表达式mapLogic.get("s")有 type Class<?>,而表达式mapLogic.get("s").newInstance()有 type Object。编译器无法判断实际实例将具有运行时类型Packet1or Packet2,因此它不知道getandsend方法应该是什么。

于 2013-03-16T22:51:46.120 回答