通过for循环对属性进行初始化,这可能吗?

时间:2014-05-02 09:47:14

标签: java constructor attributes

假设我有一个包含以下代码的类:

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

我想用以下内容初始化属性:

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

我知道代码不正确,只是为了说明。有没有办法获取当前类的属性并循环遍历属性并初始化它们?

3 个答案:

答案 0 :(得分:3)

您可以使用反射执行此操作:

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

答案 1 :(得分:1)

使用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());
    }
}

答案 2 :(得分:1)

您可以使用getDeclaredFileds方法获取实例变量

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());
    }
}