Creating a object from Class variable and calling a function on it.

Im currently at the game synchronization state with my morpg, and i’ve run into a problem.
Im using Artemis Entity Framework, and im trying to synchronize server entities with local entities.
Each entity has a set of components. I’ve created a custom Component class, called CrunchableComponent.
Basically it has 2 abstract functions : Object[] crunch(); and void decrunch(Object[] fields);
In the first one the component stores all its data, and in the second it deciphers it.

Now the problem part. Im sending a EntityCreationPacket each time a entity gets created on the server, and it contains a array of ComponentData objects, which just hold the Component’s class and the Object[] array which represent the fields.
When the client receives the packet, it should create a object of that class (f.ex. PositionComponent, which extends CrunchableComponent), cast it to CrunchableComponent, call decrunch(); on the component,
and add it to a new entity. And thats what i have trouble with.

Wouldn’t it be easier to use json?

Didn’t tought of that… Thanks.
But i still want to know if its possible to do what i want to do.
Besides its all already implemented except for the actual entity-creation-from-packet part.

Reflection:

Constructor<CrunchableComponent> ctor = klass.getConstructor();
CrunchableComponent cc = ctor.newInstance();

Thank you.
So if the klass is f.ex. PositionComponent.class (which extends CrunchableComponent), will this throw a error? And will i be able to cast it to PositionComponent?
Also, if the PositionComponent has a constructor which takes a Object[] variable as an argument, what should i write?
Thanks in advance.

Generic:


public static <T extends CrunchableComponent> T constuctComponent(Class<T> klass, Object[] data) {
    Constructor<T> ctor = klass.getConstructor(); // (assuming Object[] constructor is only constructor)
    T comp = ctor.newInstance(data); // actually, this might cause a problem with the varargs...
    return comp;
}

Thank you, i will let you know if it works :slight_smile:

If you have problems with the newInstance not passing the correct fields, try this:


T comp = ctor.newInstance(new Object[] {data}); // wrap to get through varargs destructuring

It did actually work, but the whole implementation was messy. I will try to use this again some time later, and do it properly, but for now i will stick with (Class+HashMap<String, Object>) and some IF checks. Thanks anyways, i learned something at least :slight_smile: