有效地使用setter

时间:2012-07-03 22:40:16

标签: java setter

所以,我想为bean设置一些属性。我必须设置25个变量值。我知道我可以编写25个set语句,比如bean.setProperty()。我想知道是否有更高效或更清洁的方法来做到这一点!

3 个答案:

答案 0 :(得分:0)

如果您知道属性的名称及其名称与设置者匹配,则可以使用反射。

这是一个例子(未经测试):

public String getSetterName(String property) {
    StringBuilder methodName     = new StringBuilder();
    Character     firstCharacter = Character.toUpperCase(property.charAt(0));

    methodName.append("set").append(firstCharacter).append(property.substring(1));
    return methodName.toString();
}

public void callSetters(Bean bean, String properties[], Object values[]) {
    for (int idx = 0; idx < properties.length; idx++) {
        String property   = properties[idx];
        Object value      = values[idx];
        String setterName = getSetterName(property);

        try {
            Method method = Bean.class.getMethod(setterName);
            method.invoke(bean, value);
        } catch (NoSuchMethodException nsmE) {
            // method doesn't exist for the given property, handle...
        } catch (InvocationTargetException itE) {
            // failed to invoke on target, handle...
        } catch (IllegalAccessException iaE) {
            // can't access method, handle...
        }
    }
}

此代码假设propertiesvalues具有相同的长度,并且具有从propertyvalue的一对一映射,以便任何给定索引处的值适用于同一指数的物业。

注意:这假定使用Java中的标准实践生成setter(即名为myName的属性将具有名为setMyName的setter。

答案 1 :(得分:0)

如果所有属性都是普通属性,那么最清洁的方法是使用method chaining

但是,如果要创建的对象更复杂,则应考虑使用构建器模式,其描述可在此处找到: http://rwhansen.blogspot.com/2007/07/theres-builder-pattern-that-joshua.html

答案 2 :(得分:0)

您使用的是Eclipse吗?如果是这样,一旦定义了bean类和所有类成员,只需右键单击其中一个成员变量,选择Source,然后选择“Generate Getter and Setters ...”,单击Select All按钮,然后单击OK。你已经完成了。

在Java中,您的选择是1)使变量本身公开,然后无法通过方法限制其修改,2)使它们成为受保护/私有成员变量,并且只能通过setter和getter方法进行修改,或者3)使它们成为私有的,只能通过类构造函数进行设置。