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;
}
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);
}
}
Output is:
SmallBoolean Fieldname is: smallBoolean fieldValue = false fieldValue = true bigBooleanField Fieldname is: bigBoolean fieldValue = null Exception in thread "main" java.lang.IllegalArgumentException: Can not set java.lang.Boolean field TestVO.bigBoolean to (boolean)true at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:175) at sun.reflect.UnsafeObjectFieldAccessorImpl.setBoolean(UnsafeObjectFieldAccessorImpl.java:90) at java.lang.reflect.Field.setBoolean(Field.java:795) at TestClass.main(TestClass.java:44)
i tried to set the bigBoolean value with new Boolean(true), Boolean.TRUE, true etc. nothing works. please help.
Aucun commentaire:
Enregistrer un commentaire