zoukankan      html  css  js  c++  java
  • 使用反射循环获取Bean中的属性

    平时在做项目的时候,会遇到一些比较奇葩的Bean,比如好多重复的只是序号不同的属性,例如:imgPath1,imgPath2,.....imgPath10。甚至更多(再多就是设计的问题了,对于维护的系统当然也不会去重新设计Bean,只能在有限的范围内进行优化)对于这样的属性获取时因为get方法不同看起来不能循环操作,实际上是可以使用循环的。

    对象Bean

    列出5个属性作为参考,省略了get和Set方法

    public class ForBean {
    	
    	private String imgPath1 = null;
    	
    	private String imgPath2 = null;
    	
    	private String imgPath3 = null;
    	
    	private String imgPath4 = null;
    	
    	private String imgPath5 = null;
    
    }
    

    不推荐的写法

    大多数人遇到这样的Bean时会用一下的方法写,要是属性有10个,20个,那就得重复多次。虽然不会有问题,但是显得很不优雅。

    public static void main(String[] args) {
    	
    	ForBean forBean = new ForBean();
    	
    	forBean.setImgPath1("path1");
    	forBean.setImgPath2("path2");
    	forBean.setImgPath3("path3");
    	forBean.setImgPath4("path4");
    	forBean.setImgPath5("path5");
    	
    	Map<String,String> map = new HashMap<String,String>();
    	map.put("imgPath1", forBean.getImgPath1());
    	map.put("imgPath2", forBean.getImgPath2());
    	map.put("imgPath3", forBean.getImgPath3());
    	map.put("imgPath4", forBean.getImgPath4());
    	map.put("imgPath5", forBean.getImgPath5());
    
    	System.out.println(map.toString());
    
    }
    

    以上代码输出的结果如下

    {imgPath2=path2, imgPath3=path3, imgPath1=path1, imgPath4=path4, imgPath5=path5}
    

    使用反射循环获取

    public static void main(String[] args) {
    	
    	ForBean forBean = new ForBean();
    	
    	forBean.setImgPath1("path1");
    	forBean.setImgPath2("path2");
    	forBean.setImgPath3("path3");
    	forBean.setImgPath4("path4");
    	forBean.setImgPath5("path5");
    				
    	Map<String,String> map2 = new HashMap<String,String>();
    	try {
    		for(int i=1; i <= 5; i++) {
    			Method method = forBean.getClass().getMethod("getImgPath"+i);
    			String path = (String)method.invoke(forBean);
    			map2.put("imgPath"+i, path);
    		}
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    		
    	System.out.println(map2.toString());
    
    }
    

    当然使用反射后的方法输出的结果如下,和之前的结果是一样的。虽然这样的一个改动也没有说很厉害,只是觉得代码大家都会写,不光要是会写,主要目标还是写好,这就要平时多思考多积累。

    {imgPath2=path2, imgPath3=path3, imgPath1=path1, imgPath4=path4, imgPath5=path5}
    

    反射知识

    想回顾反射的知识可以参考我之前写的博客
    反射获取一个类的私有方法
    https://www.cnblogs.com/ghq120/p/8439204.html

  • 相关阅读:
    Jmeter中的几个重要测试指标释义
    Hibernate无主键配置文件编写
    Hibernate各种主键生成策略与配置详解
    安装禅道的基本步骤
    使用Jmeter进行http接口测试
    myeclipse如何修改Web项目名称
    oracle中根据时间获取最新的一条数据
    JQuery之滑动幻灯片插件Easy Slider初体验
    比较实用的JavaScript库
    UBUNTU下SUBLIME TEXT3的安装+破解+汉化+中文输入
  • 原文地址:https://www.cnblogs.com/ghq120/p/12123470.html
Copyright © 2011-2022 走看看