java中遍历属性字段及值

来源:互联网 发布:好吃的进口零食淘宝店 编辑:程序博客网 时间:2024/05/16 17:54

转自:

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);    }}


原创粉丝点击