I am not able to set a Boolean value to a field using Java reflection.
The field data type is java.lang.Boolean. however, I am able to set the value if the data type is primitive type i.e boolean.
Here is a simple VO with Boolean type and primitive type:
public class TestVO {
private Boolean bigBoolean;
private boolean smallBoolean;
}
Run Code Online (Sandbox Code Playgroud)
Here is my java reflection code:
public class TestClass {
public static void main(String args[])
throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException {
TestVO testVO1 = new TestVO();
Class testVO = testVO1.getClass();
Field smallBooleanField = TestVO.class.getDeclaredField("smallBoolean");
Field bigBooleanField = TestVO.class.getDeclaredField("bigBoolean");
String name1 = smallBooleanField.getName();
System.out.println("SmallBoolean Fieldname is: " + name1);
smallBooleanField.setAccessible(true);
// get the value of this private field
Boolean fieldValue = (Boolean) smallBooleanField.get(testVO1);
System.out.println("fieldValue = " + fieldValue);
smallBooleanField.setAccessible(true);
smallBooleanField.setBoolean(testVO1, true);
// get the value of this private field
fieldValue = (Boolean) smallBooleanField.get(testVO1);
System.out.println("fieldValue = " + fieldValue);
name1 = bigBooleanField.getName();
System.out.println("bigBooleanField Fieldname is: " + name1);
bigBooleanField.setAccessible(true);
// get the value of this private field
fieldValue = (Boolean) bigBooleanField.get(testVO1);
System.out.println("fieldValue = " + fieldValue);
bigBooleanField.setAccessible(true);
bigBooleanField.setBoolean(testVO1, new Boolean(true));
// get the value of this private field
fieldValue = (Boolean) bigBooleanField.get(testVO1);
System.out.println("fieldValue = " + fieldValue);
}
}
Run Code Online (Sandbox Code Playgroud)
Output is:
public class TestVO {
private Boolean bigBoolean;
private boolean smallBoolean;
}
Run Code Online (Sandbox Code Playgroud)
我试图设定bigBoolean与价值new Boolean(true),Boolean.TRUE,true等什么作品。
| 归档时间: |
|
| 查看次数: |
2515 次 |
| 最近记录: |