fmsf
fmsf

Reputation: 37137

Java static initializers and reflection

Using java reflection I noticed that all classes run their static constructors when targeted by reflection. Is there any way that I can force these static constructors to return or not run them at all?

Upvotes: 4

Views: 2407

Answers (2)

blackdrag
blackdrag

Reputation: 6508

I add my answer, because I think what Bozho answers is too short now ;)

Reflection can initialize a class, only loading a class does not initialize it. Requesting the value from a static field for example does ensure the static initializer will have been called before you get the actual value. Only getting the Field usually does not. So if your reflective code causes static initializer to be executed and you really need to do it exactly like that, then there is no way to prevent those initializers from being called. If you want to avoid them getting called you have to change what you do by Reflection.

Upvotes: 0

Bozho
Bozho

Reputation: 597106

No. The static initializer is invoked as soon as the class is loaded by the classloader and initialized.

Upvotes: 7

Related Questions