jeudi 2 février 2023

Setting a field enum value with reflection

I am looping through a super classes fields and trying to set values but I am not able to do so with non primitive types. Things such as boolean, int, and double all seem to work find but when I try to use an enum object along with the plain .set() method I get a java.lang.IllegalArgumentException saying I can't cast my OffenceType field to null value even though I printed out my value first and it was not null.

       for (Field field : check.getSuperclass().getFields()) { 
               if(field.getType().equals(Integer.class)) { // This works fine
                    boolean accessible = field.isAccessible();
                    field.setAccessible(true);
                    if(field.getName().equals("violations")) field.setInt(field, getIntegerFromConfig(cfg, violationsString));
                    field.setAccessible(accessible);
                }
                else if(field.getType().equals(Check.OffenceType.class)) {
                    OffenceType offence = OffenceType.valueOf(cfg.getString(offenceString));
                    System.out.println("Type:" + offence);
                    boolean accessible = field.isAccessible();
                    field.setAccessible(true);
                    if(field.getName().equals("offence")) {
                        field.set(field, offence);
                    }
                    field.setAccessible(accessible);
                }
       }

The error is coming from the field.set(field, offence); line also the field it is trying to access is labeled as public OffenceType offence;

The following is the stack trace

[13:19:24 WARN]: java.lang.IllegalArgumentException: Can not set me.HowDoISolveThis.check.Check$OffenceType field me.HowDoISolveThis.check.offence to null value
[13:19:24 WARN]:        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
[13:19:24 WARN]:        at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
[13:19:24 WARN]:        at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
[13:19:24 WARN]:        at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
[13:19:24 WARN]:        at java.lang.reflect.Field.set(Field.java:764)
[13:19:24 WARN]:        at me.HowDoISolveThis.config.Config.updateConfig(Config.java:125)```




Aucun commentaire:

Enregistrer un commentaire