Java Object with protected initializer (libgdx box2d Body)


I started to migrate my code from java to kotlin (I like it better, and actively using something is the way to find bugs). On one of my objects I have to store a body value, But I can only set it after the object was created.

The problem is: because the initializer of the Body class is protected (it can only be created through a world) It gives me an error when I try create the field for it.
I’ll probably find a workaround for it, (The last resort is to keep it in java) but I would like to get some options.


Could you please post a complete example showing what you’re trying to do?


Is it like gson type token?


The java version:

public EntityHolder object;

public Body  body; << The field what I need to set after the object was created.
protected boolean act(Fixture f1, int value) {
    count +=value;
    try {
        if (((Entity) f1.getBody().getUserData()).getComponent(IdentifierComponent.class).type == IdentifierComponent.Type.Player.value)
            if(count ==1) {
                object.exists = false;
            return false;
    } catch (Exception e) {,e.toString());

The object is being obtained from a pool, so there is no way to set the body variable while initializing. I tried to set it to a “blank” body, but since the init method is protected that’s not an option.
I see the point, but (I’m sure to be wrong) it might kill pooling if there is no option to create a field like this.
(android code, I know theres a way to not to loose performance with getters and setters, but it was dismantling the apis I use so I opted it out for now)

Libgdx uses a native implementation of Box2d, all the code is behind a Wrapper.

public class WheeledBody implements Component,Pool.Poolable {
public Body body;
public Body foot;
public RevoluteJoint motor;
public boolean exists = false;
public boolean wallblocked = true;

public float Speed;
public boolean isMoving=true;
public boolean Forward=true;
public Sensor groundSensor;
public Sensor headSensor;
public Sensor leftSensor;
public Sensor rightSensor;
public float TORQUE;
public void reset() {
    exists =false;
    groundSensor = null;
    leftSensor = null;
    rightSensor = null;
    headSensor = null;
    wallblocked = true;
    isMoving = true;
    Forward = true;


Also using ashly, and this is how they meant to use it.
So, I am having something whitch would be (Just read about it) data class, but its also having a reset method to set it to the defaults.


If you’re certain that body won’t be accessed before it is initialized you can set it as lateinit var body: Body which will allow you to postpone initialization, otherwise I’m afraid you’ll have to make the body a nullable type and use if checks.


Sorry for not replying, I found that solution, and now it works.