`
方块石
  • 浏览: 59993 次
  • 来自: ...
社区版块
存档分类
最新评论

理解反射(摘自网上)

阅读更多
package list2Xml;

import java.lang.reflect.Field;  
import java.lang.reflect.Method;  
import java.util.ArrayList;  
import java.util.List;  
 
public class Change {  
 
    public String toXml(List list) {  
        StringBuffer bf = new StringBuffer();  
 
        bf.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<objects>\n");  
        for (int i = 0; i < list.size(); i++) {  
            Object obj = list.get(i);  
            //getSimpleName返回getClass()对象的简称
            bf.append("\t<" + obj.getClass().getSimpleName());
            //getDeclaredFields返回对象中所有字段,包括私有的
            Field[] fields = obj.getClass().getDeclaredFields();  
            for (int j = 0; j < fields.length; j++) {  
                try {  
                    String name = fields[j].getName();  
                      
                    Method method = obj.getClass().getMethod(  
                            "get" + name.substring(0, 1).toUpperCase()  
                                    + name.substring(1), new Class[] {}); 
                    //invoke调用源对象的方法,也就是obj对象的method方法,如果有返回值,则返回.  如果method有参数,则是在new Object[]{}中传值
                    Object result = method.invoke(obj, new Object[] {});  
                    bf.append(" " + name + "=" + result);  
                } catch (Exception e) {  
 
                }  
            }  
            bf.append(" />\n");  
        }  
        bf.append("</objects>\n");  
        return bf.toString();  
    }  
 
    public static void main(String[] args) {  
        List<User> list = new ArrayList<User>();  
        User user1 = new User();  
        user1.setId("i1");  
        user1.setName("n1");  
        User user2 = new User();  
        user2.setId("i2");  
        user2.setName("n2");  
        list.add(user1);  
        list.add(user2);  
        Change c = new Change();  
        System.out.println(c.toXml(list));  
    }  
 

   

class User {


public String id;

public String name;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics