方法在哪里?

时间:2013-03-16 22:44:01

标签: java

我的来源:

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()&lt; ---获取或发​​送不可用

我如何获得这些方法?

1 个答案:

答案 0 :(得分: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")的类型为Class<? extends Packet>,表达式mapLogic.get("s").newInstance()的类型为Packet

现在的方式,表达式mapLogic.get("s")的类型为Class<?>,而表达式mapLogic.get("s").newInstance()的类型为Object。编译器无法告诉实际实例将具有运行时类型Packet1Packet2,因此它不知道getsend方法应该是什么是。