java获取一个类中所有属性名和属性值


获取属性名和属性值

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


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM