[英]Java class list like in Python
I have classes which are inherited from abstract Packet( this class has abstract method named read which reads from ByteBuffer).我有从抽象数据包继承的类(这个 class 有一个名为 read 的抽象方法,它从 ByteBuffer 读取)。
in Python i would do something like...在 Python 我会做类似的事情......
class Blabla(Packet):
pass
class Blabla2(Packet):
pass
and then i would init each class in list like this然后我会像这样在列表中初始化每个 class
_packets = [Blabla, Blabla2]
and when i would identify id of packet i would do like this当我识别数据包的ID时,我会这样做
pck = _packets[packetId]()
Want to do the same in java.想在 java 中做同样的事情。 Is there any fast way(except using switch)
有什么快速的方法(使用开关除外)
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()
.也许您正在寻找
Class#newInstance()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.