mercredi 29 août 2018

Is it possible to change the default initial field value via reflection in java?

lets say we have a class with an field and it has a default initial value and that is not changed by the constructor, for example

public class Server {
  private int pingFrequency = 500;

  public Server() {
  }
}

Now I want't to change the default initial value to another value BEFORE the object is constructed. The reason is that this class is used by an library and hide away the object instance. So I could only control when the object is constructed but not where and how.

I've tried to get field via reflection, but I dont't see any way to change the default value

Field pingFrequency =  Class.forName("Server").getDeclaredField("pingFrequency")

I think I must change something in the classloader, but I don't know what and how.

Thank you





Aucun commentaire:

Enregistrer un commentaire