无法通过反射设置布尔值

我无法Boolean使用Java反射将值设置为字段。字段数据类型为java.lang.Boolean。但是,如果数据类型是基本类型,即I,我就可以设置该值boolean

这是带有Boolean类型和原始类型的简单VO :

public class TestVO {

private Boolean bigBoolean;

private boolean smallBoolean;

}

这是我的java反射代码:

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);

}

}

输出为:

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)


我试图设定bigBoolean与价值new Boolean(true)Boolean.TRUEtrue等什么作品。

回答:

根据此,bigBoolean.setBoolean()被调用以设置一个字段,该字段是用原语类型的值的参考布尔类型。在非反射等效项中Boolean

val = true,编译器会将原始类型’true’转换(或装箱)为引用类型,new Boolean(True)以便其类型检查将接受该语句。

以上是 无法通过反射设置布尔值 的全部内容, 来源链接: utcz.com/qa/421887.html

回到顶部