實體Bean Carjava
package com.mytest.testcase1;
public class Car {
//品牌
private String mBrand;
//類型
private String mSort;
//排量
private int outPutVol;
public String getmBrand() {
return mBrand;
}
public void setmBrand(String mBrand) {
this.mBrand = mBrand;
}
public String getmSort() {
return mSort;
}
public void setmSort(String mSort) {
this.mSort = mSort;
}
public int getOutPutVol() {
return outPutVol;
}
public void setOutPutVol(int outPutVol) {
this.outPutVol = outPutVol;
}
}
複製代碼
經過反射獲取實例對象的field進行判空bash
package com.mytest.testcase1;
import java.lang.reflect.Field;
public class TestCar {
public static void main(String[] args) throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException, ClassNotFoundException {
Car carInstance = new Car();
carInstance.setmBrand("Audi");
carInstance.setmSort(null);
carInstance.setOutPutVol(2);
Class<?> clzz = carInstance.getClass();
Field[] fields = clzz.getDeclaredFields();
for(Field field : fields ) {
Field f = clzz.getDeclaredField(field.getName());
f.setAccessible(true);
Object obj = (Object)f.get(carInstance);
if(null == obj) {
System.out.println(field.getName() + " is null");
} else {
System.out.println(field.getName() + " is " + obj);
}
}
}
}
複製代碼
輸出:ui
mBrand is Audithis
mSort is nullspa
outPutVol is 2code