lundi 15 juin 2015

java - How to update members in the hierarchy using reflection

I have a class called Volvo that inherits from car.
It contains a class called Engine that contains Valve.

public class Engine {

    public Engine(int e, int f) {
        this.e = e;
        valve = new Valve(f);
    }

    private int e;
    private Valve valve;
}

valve has a single data member - int f;

public class Valve {
    public Valve(int f) {
        this.f = f;
    }

    public int f;
}

Everything is private and does not contain a setter.

I want to set a value using reflection with the following string

fillIn(volvo, "Engine.Valve.f", 10);

Using this code:

String[] splits = path.split("\\.");
Class tmpClass = obj.getClass();

for (int i = 0; i < splits.length; i++) {
    if (i + 1 != splits.length) {
        Field field = tmpClass.getDeclaredField(splits[i]);
        tmpClass = field.getClass();
    } else {
        System.out.println("**** - " + splits[i]);
    }
}

Problems:
1. My object is Volvo. the engine is located at car. can I get the field when iterating on volvo.
2. How do I set the value? the type is different every time.
3. Is there a better practice (FW?) that can do this?

Thanks.





Aucun commentaire:

Enregistrer un commentaire