获取属性名和属性值
public static void outprint(String s1, Object o) {
try {
Class c = Class.forName(s1);
Field[] fields = c.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
}
System.out.println("-----------------" + s1 + "-----------------");
for (Field f : fields) {
String field = f.toString().substring(f.toString().lastIndexOf(".") + 1);
System.out.println(field + " ->>\t" + f.get(o));
}
} catch (ClassNotFoundException | IllegalAccessException e) {
e.printStackTrace();
}
}
Poi类
package beans;
public class Poi {
private double x;
private double y;
private int code;
public Poi() {
}
public Poi(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
@Override
public String toString() {
return "[" + x +", " + y + "]";
}
}
Main函数
public static void main(String[] args) throws IOException {
Poi poi = new Poi(123, 234);
outprint("beans.Poi", poi);
}
输出内容
-----------------beans.Poi-----------------
x ->> 123.0
y ->> 234.0
code ->> 0