mercredi 20 février 2019

IllegalArgumentException while setting a java class field via reflection

everyone:

I'm working on using java reflection to set a field's value, but get IllegalArgumentException

I find a oracle tutorial, https://docs.oracle.com/javase/tutorial/reflect/member/fieldTrouble.html which is very similar to my case.

But even if I follow the example to use,

f.set(ft, new Integer(43));

It still fails with the same exception.

The update problematic code is:

import java.lang.reflect.Field;

public class FieldTrouble {
  public Integer val;

  public static void main(String... args) {
    FieldTrouble ft = new FieldTrouble();
    try {
      Class<?> c = ft.getClass();
      Field f = c.getDeclaredField("val");
      f.setInt(ft, new Integer(43));               // IllegalArgumentException

      // production code should handle these exceptions more gracefully
    } catch (NoSuchFieldException x) {
      x.printStackTrace();
    } catch (IllegalAccessException x) {
      x.printStackTrace();
    }
  }
}

I use java 1.8 Does anyone have any idea of how to solve this? Thanks





Aucun commentaire:

Enregistrer un commentaire