一、javabean反射工具类,可以在控制台中输出一个对象的属性值列表
public class ReflectionUtil {
public static boolean isShow = true; //是否启用
/**
* 获得一个对象的属性值
* @author:qiuchen
* @createTime:2012-7-4
* @param obj 目标对象
*/
@SuppressWarnings("unchecked")
public static void getFieldValue(Object obj){
if (isShow) getFieldValue(obj, isShow);
}
/**
* 获得一个对象的属性值
* @author:qiuchen
* @createTime:2012-7-4
* @param obj 目标对象
*/
@SuppressWarnings("unchecked")
private static void getFieldValue(Object obj,boolean isShow){
Class cls = obj.getClass();
Method[] methods = cls.getDeclaredMethods();//获得类的方法集合
StringBuffer buffer = new StringBuffer();
try {
for (Method method : methods) {
if(method!=null && method.getName().startsWith("get")){
Object value = method.invoke(obj, null);
value = method.getName().substring(3)+":"+value+",";
buffer.append(value);
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(cls.toString()+"["+buffer.toString()+"]");
}
public static void main(String[] args) {
}
}
二、F盘的属性文件内容
### fastjs### fastjson操作JSON ###
json1={"name":"cena","age":"35","sex":"男"}
json2=[{"name":"cena","age":"35","sex":"男"},{"name":"hhh","age":"37","sex":"男"},{"name":"ever","age":"25","sex":"女"}]
json3={"name":"cena","age":"35","sex":"男","hobbies":[{"name":"踢球","hYear":"2年"},{"":"","":""}]}
三、FastJson工具类
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ttpod.slt.model.Hobby;
import com.ttpod.slt.model.User;
public class JsonUtil {
/**
* 从json字符串中解析出java对象
* @author:qiuchen
* @createTime:2012-7-8
* @param jsonStr json格式字符串
* @param clazz java类
* @return clazz的实例
*/
public static Object parseJavaObject(String jsonStr,Class clazz){
return JSON.toJavaObject(JSON.parseObject(jsonStr), clazz);
}
/**
* 测试方法
* @author:qiuchen
* @createTime:2012-7-8
* @param args
*/
public static void main(String[] args) {
//0.0加载属性文件(所有json字符串从文件中读取)
Properties pp = PropertiesUtil.getProperties("f:/properties.properties");
//0.1简单格式的json字符串
String json1 = pp.getProperty("json1");
System.out.println(json1);
User user = (User)JsonUtil.parseJavaObject(json1,User.class);
ReflectionUtil.getFieldValue(user);
//0.2数组形式的json字符串
String json2 = pp.getProperty("json2");
System.out.println(json2);
JSONArray array = JSONArray.parseArray(json2);
List
for(int i = 0; i < array.size();i++){
JSONObject jobj = (JSONObject)array.get(i);
User user2 = JSON.toJavaObject(jobj,User.class);
userList.add(user2);
}
for(User u : userList){
ReflectionUtil.getFieldValue(u);
}
//0.3复杂数组形式的json字符串
String json3 = pp.getProperty("json3");
System.out.println(json3);
User user3 = (User)JsonUtil.parseJavaObject(json3, User.class);
ReflectionUtil.getFieldValue(user3);
for(Hobby h : user3.getHobbies()){
ReflectionUtil.getFieldValue(h);
}
}
}