java中遍历属性字段及值

转自:

http://bbs.csdn.net/topics/320176897



示例代码如下:

package test;

import java.lang.reflect.Field;

interface IEntity{

}

class Entity implements IEntity{
    private String s1 = "字符串1";

    private String s2 = "字符串2";
}

public class Test {
    
    public static void reflect(IEntity e) throws Exception{
        Class cls = e.getClass();
        Field[] fields = cls.getDeclaredFields();
        for(int i=0; i<fields.length; i++){
            Field f = fields[i];
            f.setAccessible(true);
            System.out.println("属性名:" + f.getName() + " 属性值:" + f.get(e));
        } 
    }
    
    public static void main(String[] args) throws Exception{
        IEntity e = new Entity();
        reflect(e);
    }
}


posted on 2013-01-07 10:02  bwgang  阅读(304)  评论(0编辑  收藏  举报

导航