java獲取一個類中所有屬性名和屬性值
阿新 • • 發佈:2021-10-22
獲取屬性名和屬性值
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