开发者

Java class list like in Python

I have classes which are inher开发者_开发百科ited from abstract Packet( this class has abstract method named read which reads from ByteBuffer).

in Python i would do something like...

class Blabla(Packet):
    pass
class Blabla2(Packet):
    pass

and then i would init each class in list like this

_packets = [Blabla, Blabla2]

and when i would identify id of packet i would do like this

pck = _packets[packetId]()

Want to do the same in java. Is there any fast way(except using switch)


Yes, it is possible to do something very similar in Java.

You could have a list of Class objects and then call list.get(packetId).newInstance() to create an instance of the correct class.

See the Javadoc.


This is what you should do:

ArrayList<Class> list = new ArrayList<Class>();
list.add(Class.forName("Blabla"));
list.add(Class.forName("Blabla2"));

list.get(packetId).newInstance();


Maybe you are looking for Class#newInstance().

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜