vendredi 24 juillet 2020

Get subclass back when stored as superclass

So I've been trying to fix this for a few hours now, to no avail.

Basically, I have class A, and class B which extends A. A has a string field "name", and another field "id", class B changes name when instantiated. B is then later stored as A, and the only thing identifying that A class to the B class is the "id" field.

I need a way to get the changed "name" that the B class has, from the A class.

Here's a code example:

class A {
    public String name = "test";
    public String id = "A_ID";
    
    public A(String id) {
        if (id.equals("B_ID") {
            // how would I get the name field of the B class, without instantiating B
        }
    }
}
class B extends A {
    {
        name = "test1";
        id = "B_ID";
    }
}

And here's what I've tried:

class A {
    public static Map<String, Class<? extends A> REGISTRY = new HashMap<>();
    
    public String name = "test";
    public String id = "A_ID"; // is B_ID when changed
    
    public Object getField(String key) {
        Field field = REGISTRY.get(this.id).getSuperclass().getDeclaredField(key);
        return field.get(this); // <- the issue
    }
}
class B extends A {
    static {
        REGISTRY.put("B_ID", B.class);
    }
    public B() {
        name = "test1";
        id = "B_ID";
    }

}

Here's the problem with my solution, passing this to field.get(this) returns the fields of the current A object, which is what we already have. I need the fields that B changes when instantiated, but when B gets instantiated it calls getField a few times, which then causes a perpetual loop, I need a way to get the fields from B without instantiating B.

I've tried casting A to B but that causes a ClassCastException.

Sorry that this is confusing, I can't send the entire class as it's literally 1k+ lines, but basically the ID field is the only data stored with A that remains from B, and I need a way to get the fields from B without instantiating it





Aucun commentaire:

Enregistrer un commentaire