lundi 20 mars 2017

Java Reflection // Can not set java.lang.Boolean to (boolean)true [duplicate]

This question already has an answer here:

I have a class which has a field named "bool" of type java.lang.Boolean and try to set its value via reflection with the following code:

MyClass myClass = new MyClass();
try {
    Field field = myClass.getClass().getField("bool");
    field.setBoolean(myClass, true);
} catch (Throwable ex) {
    ex.printStackTrace();
}

I always get the following error: java.lang.IllegalArgumentException: Can not set java.lang.Boolean field MyClass.bool to (boolean)true

Passing an instance of new Boolean instead of true, Boolean.TRUE, or new Boolean(true).booleanValue() didn't work either. Interestingly, it works flawlessly if I change the type of java.lang.Boolean to boolean. However, I need to be able to process java.lang.Boolean, too.

How can I set a java.lang.Boolean via reflection?





Aucun commentaire:

Enregistrer un commentaire