我无法使用java反射将布尔值设置为字段。 字段数据类型是java.lang.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的是:smallBoolean fieldValue = false fieldValue = true bigBooleanField Fieldname is:bigBoolean fieldValue方法= NULL 异常在线程 “主” java.lang.IllegalArgumentException异常:不能sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)设置一个java.lang.Boolean场TestVO.bigBoolean到(布尔)真 在sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:175) 在sun.reflect.UnsafeObjectFieldAccessorImpl.setBoolean(UnsafeObjectFieldAccessorImpl.java:90) 在java.lang.reflect.Field.setBoolean(Field.java:795) 在TestClass.main(TestClass.java:44)
我试图设置用new Boolean(true),Boolean.TRUE,true等的bigBoolean值无效。请帮忙。
感谢您的详细解答和解决方案。 +1。 –