遍历一个对象的属性名称和值到map中,然后进行URL地址的拼接
先说下需求:要求通过URL进行地址的拼接,URL=(URL地址)?A=2012-8-5&B=bbb&C=ccc,传递给web页面,进行URL值的传递。
具体实现看下面的代码吧:
public class Test3 {
public static void main(String[] args) {
TestBean tb = new TestBean();
tb.setA("2012-8-5");
tb.setB("bbb");
tb.setC("ccc");
try {
HashMap<String, String> map = readClassAttr(tb);
String url = getUrl(map);
System.out.println(url);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 用来遍历对象属性和属性值
*/
public static HashMap<String, String> readClassAttr(Object tb) throws Exception {
HashMap<String, String> maps = new HashMap<String, String>();
Field[] fields = tb.getClass().getDeclaredFields();
System.out.println(fields.length);
for (Field field : fields) {
field.setAccessible(true);
if (field.get(tb) != null && !"".equals(field.get(tb).toString())) {
maps.put(field.getName(), field.get(tb).toString());
//field.getName()获取该对象的属性
//field.get(tb).toString()获取该对象属性所对应的值
}
}
return maps;
}
/**
* 地址拼接
*/
private static String getUrl(HashMap<String, String> params) {
//此处URL为web给你的链接地址
String url = "URL";
// 添加url参数
if (params != null) {
Iterator<String> it = params.keySet().iterator();
StringBuffer sb = null;
while (it.hasNext()) {
String key = it.next();
String value = params.get(key);
if (sb == null) {
sb = new StringBuffer();
sb.append("?");
} else {
sb.append("&");
}
sb.append(key);
sb.append("=");
sb.append(value);
}
url += sb.toString();
}
return url;
}
}
TestBean 类:
public class TestBean {
String A;
String B;
String C;
public String getA() {
return A;
}
public void setA(String a) {
A = a;
}
public String getB() {
return B;
}
public void setB(String b) {
B = b;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
}