简单的通过动态属性名获取属性值
一个简单的JAVA对象
public class platformBean {
private String platName1;
private String platLink1;
private String platName2;
private String platLink2;
private String platName3;
private String platLink3;
private String platName4;
private String platLink4;
private List<tempPlat> listPlat;
}
public class tempPlat {
private String platName;
private String platLink;
}
package com.lovo.test;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import com.lovo.beans.platformBean;
import com.lovo.beans.tempPlat;
public class reflexTest {
public static Object getValeByReflex(String key,Object obj)
{
//获取对象文件数组
Field[] fieldes = obj.getClass().getDeclaredFields();
for (Field field : fieldes) {
//设置权限
field.setAccessible(true);
//field.getName() 获取属性名
if(key.equals(field.getName()))
{
try
{
//获取属性值
return field.get(obj);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
public static void main(String[] args) {
platformBean bean = new platformBean("平台1", "连接1", "平台2", "连接2", null, null, null, null);
List<tempPlat> platList = new ArrayList<tempPlat>();
for(int i=1;i<5;i++)
{
String plat ="platName"+i;
String link ="platLink"+i;
plat = (String) getValeByReflex(plat, bean);
link= (String) getValeByReflex(link, bean);
if(StringUtils.isNotEmpty(plat)&&StringUtils.isNotEmpty(link))
{
tempPlat temp = new tempPlat();
temp.setPlatName(plat);
temp.setPlatLink(link);
platList.add(temp);
}
}
bean.setListPlat(platList);
System.out.println(bean);
}
}
网友评论