数据属性转换

代码一:

public class User
{
    private String username;
    private String passowrd;

    public String getUsername()
    {
 return username;
    }

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

    public String getPassowrd()
    {
 return passowrd;
    }

    public void setPassowrd(String passowrd)
    {
 this.passowrd = passowrd;
    }
}

代码2:

public class Test
{
 public static void main(String[]args) throws Exception
 {
  User user = new User();
  user.setUsername("aaaa");
  user.setPassowrd("hhhh");
  Field[] fields =   user.getClass().getDeclaredFields();

  //这句很重要,设置属性是否保护
  java.lang.reflect.AccessibleObject.setAccessible(fields, true);
  for (Field field : fields)
  {
      System.out.println(field);
     
      System.out.println(field.get(user));
  }
  java.lang.reflect.AccessibleObject.setAccessible(fields, false);
 }
}

即可取得对象的所有属性值

你可能感兴趣的:(转换)