安卓中Property类的用途是什么?

4
2个回答

2

属性是对反射的封装。

例如,您有一个对象

public class A {
    private int fieldOfA;
    private int fieldTwo;
    private int fieldThree;

    public void setFieldOfA(int a) {
        fieldOfA = a;
    }

    public int getFieldOfA() {
        return fieldOfA;
    }

    public void setFieldTwo(int a) {
        fieldTwo = a;
    }

    public int getFieldTwo() {
        return fieldTwo;
    }

    public void setFieldThree(int a) {
        fieldThree = a;
    }

    public int getFieldThree() {
        return fieldThree;
    }
}

如果您需要更新某些字段,而没有使用Properties,则必须在更新方法中知道它们的所有名称。
private void updateValues(final A a, final int value) {
    a.setFieldOfA(value);
    a.setFieldTwo(value);
    a.setFieldThree(value);
}

使用 Properties,您可以仅更新属性。
Property aProperty = Property.of(A.class, int.class, "fieldOfA");
Property bProperty = Property.of(A.class, int.class, "fieldTwo");
Property cProperty = Property.of(A.class, int.class, "fieldThree");

Collection<Property<A, Integer>> properties = new HashSet<>();
properties.add(aProperty);
properties.add(bProperty);
properties.add(cProperty);

updateValues(a, 10, properties);

这种方法将会是:

private void updateValues(final A a, final int value, final Collection<Property<A, Integer>> properties) {
    for (final Property<A, Integer> property : properties) {
        property.set(a, value);
    }
}

正如laalto所述,属性动画使用类似的机制。

1
一个例子就是属性动画。Property类提供了一个抽象,用于表示可以随着时间改变以执行动画的属性。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接