举个例子,一个实体类Fruit中有apple、pear、banana等几十个int类型变量。
而数据库中是按照如下方式存储的,type表示水果类型,1是apple,2是pear
count, type, date
1, 1, 2019-01-01
6, 2, 2019-01-01
-3, 2, 2019-01-02
需要统计出每天的水果数量变动,怎么样根据type选取setter,用if或者switch感觉代码太过臃肿了,有没有更科学的方式
首先需要一个map或者enum由于关联type和具体的水果名称,比如apple,"1":"apple"
然后通过数据库查询数据后,需要一个map用于存储每个type具体的变动,比如"1":"1"
最后通过反射,通过方法名,循环类的所有方法,对比第一个map中的apple拼接方法名setApple获取对应的方法,将第二个map中的值作为参数,调用该方法。
做个类型值与类型变量的映射,比如用map,从数据库查询后当前行的count对应的类型就是map.get(type值)
public class Bean {
private int apple, pear, banana;
public int getApple() {
return apple;
}
public void setApple(int apple) {
this.apple = apple;
}
public int getPear() {
return pear;
}
public void setPear(int pear) {
this.pear = pear;
}
public int getBanana() {
return banana;
}
public void setBanana(int banana) {
this.banana = banana;
}
}
public static void main(String[] args) {
//1 苹果 10个
Bean bean=new Bean();
setType(bean,1,10);
//2 梨 15个
setType(bean,2,15);
//3 香蕉 20个
setType(bean,3,20);
System.out.println("苹果有"+bean.getApple());
System.out.println("梨有"+bean.getPear());
System.out.println("香蕉有"+bean.getBanana());
}
private static Bean setType(Bean bean,int type,int count) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "Apple");
map.put(2, "Pear");
map.put(3, "Banana");
try {
Method method = bean.getClass().getMethod("set" + map.get(type), int.class);
method.invoke(bean, count);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return bean;
}
输出
苹果有10
梨有15
香蕉有20