获取Java对象的所有属性和方法
2017-02-15 本文已影响760人
积微微微
Java开发中遍历Java对象,获取对应的属性和值。主要用到java.lang.reflect.Field这个类
废话不多说,上代码。
//示例类
public class Host{
private String ip;
private int port;
private String name;
private List<String> child;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getChild() {
return child;
}
public void setChild(List<String> child) {
this.child = child;
}
}
//
public class ReduceObject {
public static void main(String[] args){
Host host= new Host();
host.setIp("192.168.145.130");
host.setName("redisNode");
host.setPort(5000);
Field [] fields = refrect(host);
for(int i=0;i<fields.length;i++){
Field f = fields[i];
f.setAccessible(true);//设置属性可读
try {
System.out.println("host["+f.getName()+"] = "+f.get(host));
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
//获得所有属性数组
public static Field[] refrect(Host host){
Class cls = host.getClass();
Field[] fields = cls.getDeclaredFields();
return fields;
}
}