获取Java对象的所有字段值

119 阅读1分钟

问题

在对接第三方的请求接口时,POST传参要求的格式类似GET的params; 请求内容类型,这里为 application/x-www-form-urlencoded 标准的编码格式,数据被编码为名称/值对。 username=username&password=password&type=1&type=2 #问题解析

  • 方法一: 将对象转为List的list,用HttpPost请求类时,可将list转为JsonString放入entity. 具体方式请查看此例
  • 方法二: 将对象转为 username=username&password=password&type=1&type=2 格式.在此方法中重写了方法类的toString();
public String toString() {
String s = "";
  Field[] fields = this.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            try {
                s += field.getName()+"="+field.get(this).toString()+"&";
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
}

测试Demo如下

public class TestDemo {

    public static void main(String[] args) {
        Test test = new Test("zhangsan","123456","2");
        System.out.println("test.toString() = " + test.toString());
    }
    static class  Test{
        private String username;
        private String password;
        private String type;

        public Test(String username, String password, String type) {
            this.username = username;
            this.password = password;
            this.type = type;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getType() {
            return type;
        }

        public void setType(String type) {
            this.type = type;
        }

        @Override
        public String toString() {
            String s = "";
            Field[] fields = this.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                try {
                    s += field.getName()+"="+field.get(this).toString()+"&";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return s;
        }
    }
}

测试结果如下

image.png