Question

Let's say I have a class with the following code:

private String attribute1;
private String attribute2;
private String attribute3;
.....
.....
.....

And I want to initialize the attributes by something like:

public constructor() {
    int fixedLength = this.getAttributes.size();
    for(int i = 0; i < fixedLength; i++) {
        this.getAttributes.get(i).set("My string is: " + i);
    }
}

I know the code is not correct, just for illustration. Is there a way to get the attributes of the current class and loop through the attributes and initialize them?

Was it helpful?

Solution

You can do this using reflection:

MyClass.class.getField("attribute" + i).set(..);

OTHER TIPS

Use an EnumMap:

Map<Attribute,String> attributes = new EnumMap<>(Attribute.class);

enum Attribute {
    One,
    Two,
    Three;
}

public void constructor() {
    for ( Attribute a : Attribute.values() ) {
        attributes.put(a, "My string is: "+a.name());
    }
}

You could use getDeclaredFileds method to get instance variables

public void setAttributes(Object obj) throws Exception {
    Class<?> objClass = obj.getClass();

    Field[] fields = objClass.getDeclaredFields();
    for(Field field : fields) {
        String name = field.getName();
        field.set(obj, "My Value");

        Object value = field.get(obj);
        System.out.println(name + ": " + value.toString());
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top