java中对象属性值为null ,对属性值进行赋值

  • Post author:
  • Post category:java


import java.lang.reflect.Field;

public class TestUtil {



private int id;

private int age;

private String personName;

public String identitify;

protected String address;

private String phone;



public int getId() {



return id;



}



public void setId(int id) {



this.id = id;



}



public int getAge() {



return age;



}



public void setAge(int age) {



this.age = age;



}



public String getPersonName() {



return personName;



}



public void setPersonName(String personName) {



this.personName = personName;



}



public String getIdentitify() {



return identitify;



}



public void setIdentitify(String identitify) {



this.identitify = identitify;



}



public String getAddress() {



return address;



}



public void setAddress(String address) {



this.address = address;



}



public String getPhone() {



return phone;



}



public void setPhone(String phone) {



this.phone = phone;



}












@Override



public String toString() {



return “TestUtil [id=” + id + “, age=” + age + “, personName=”



+ personName + “, identitify=” + identitify + “, address=”



+ address + “, phone=” + phone + “]”;



}



public static void main(String[] args) throws Exception, IllegalAccessException {



TestUtil test111 = new TestUtil();



test111.setAge(18);



test111.setIdentitify(“111111111111111111111”);



test111.setPhone(“138888888888”);



for (Field f : test111.getClass().getDeclaredFields()) {



f.setAccessible(true);



if (f.get(test111) == null){ //判断字段是否为空,并且对象属性中的基本都会转为对象类型来判断





f.set(test111, “778878”);





System.out.println(f.getName());



}



}



System.out.println(test111.toString());






}

}

运行结果

personName

address

TestUtil [id=0, age=18, personName=778878, identitify=111111111111111111111, address=778878, phone=138888888888]



版权声明:本文为haohan_lt原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。