Cannot set Boolean value through reflection

Sri*_* KK 5 java reflection

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等什么作品。

Yoh*_*iam 5

根据此,bigBoolean.setBoolean()被调用以设置一个字段,该字段是用原语类型的值的参考布尔类型。在非反射等效项中Boolean val = true,编译器会将原始类型'true'转换(或装箱)为引用类型,new Boolean(True)以便其类型检查将接受该语句。

使用反射时,类型检查仅在运行时发生,因此没有机会将值装箱。IllegalArgumentException由于不可转换类型,这会强制抛出