1

I have classes which are inherited 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)

0

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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();

Comments

2

Maybe you are looking for Class#newInstance().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.