例子:
public class User{
private String name;
private String age;
private String address;
.... set and get methods....
}
User user = new User();
user.setName("albert");
user.setAge("22");
我想将用户对象转换成这个字符串
name=albert&address=&age=22
因为我使用 new URL()
来发布这个字符串。
我有很多其他的对象要转换成这个字符串,所以我想要一个工具方法
有什么好办法吗?
提前致谢
最佳答案
对任何对象类型使用反射:
import java.lang.reflect.Field;
public class ObjectToPostStringbyReflection {
public String getPostParamString(Object o) throws IllegalArgumentException, IllegalAccessException{
Class<? extends Object> clazz = o.getClass();
StringBuilder sb = new StringBuilder();
for(Field f : clazz.getDeclaredFields()){
f.setAccessible(true);
if(!sb.toString().isEmpty()){
sb.append("&");
}
sb.append(f.getName())
.append("=")
.append(f.get(o));
}
return sb.toString();
}
/**
* @param args
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
// TODO Auto-generated method stub
User user = new User();
user.setName("John");
user.setAddress("address");
user.setAge("18");
ObjectToPostStringbyReflection reflector = new ObjectToPostStringbyReflection();
System.out.println(reflector.getPostParamString(user));
}
}
结果:name=John&age=18&address=address
关于java - 如何将javabean转换为post参数字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39145419/