[英]Univerzal class setter - Java
Since I have a class with 8 parameters (p1,p2,...), all of type boolean, I was wondering if it is possible to create a setter method that has two parameters : object's variable member (to determine which of p1,p2,... to set) and a value , instead of creating 8 different setters). 由于我有一个带有8个参数(p1,p2,...)的类,都是boolean类型,所以我想知道是否可以创建一个具有两个参数的setter方法:对象的变量成员 (确定p1中的哪个, p2,...进行设置)和一个value ,而不是创建8个不同的setter)。
Let's say we have following class: 假设我们有以下课程:
public class SomeClass{
private boolean p1;
private boolean p2;
private boolean p3;
private boolean p4;
private boolean p5;
private boolean p6;
private boolean p7;
private boolean p8;
}
How is it possible to create an univerzal setter for any of those p1-p8 ? 如何为这些p1-p8中的任何一个创建一个通用设置器 ? Something like:
就像是:
public void setP(SomeClass.param p, boolean value)
You can use BeanUtils
from apache commons 您可以从apache commons使用
BeanUtils
void setP(String name, Boolean value) {
BeanUtils.setProperty(this, name, value);
}
or using an int 或使用int
void setP(Integer i, Boolean value) {
BeanUtils.setProperty(this, "p"+i.toString(), value);
}
generally speaking it works, but be aware it is not totally safe, since both name or i can assume illegal values and you should better add a some sanity check, otherwise you can get an IllegalAccessException
or an InvocationTargetException
. 通常来说,它是可行的,但是要知道它并不完全安全,因为name或i都可以采用非法值,因此您最好添加一些健全性检查,否则可以获取
IllegalAccessException
或InvocationTargetException
。 The advantage of using the 8 setter is of course compile time checking, and your ide can write them for you. 当然,使用8 setter的好处是可以检查编译时间,并且您的ide可以为您编写它们。 And of course, as suggested, this library is using reflection.
当然,正如建议的那样,该库正在使用反射。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.