简体   繁体   English

Java静态初始化程序和反射

[英]Java static initializers and reflection

Using java reflection I noticed that all classes run their static constructors when targeted by reflection. 使用java反射时,我注意到所有类在以反射为目标时都运行其静态构造函数。 Is there any way that I can force these static constructors to return or not run them at all? 有什么方法可以强制这些静态构造函数返回或根本不运行它们?

否。类加载器加载并初始化该类后,便会立即调用静态初始化程序。

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. 如果要避免打电话给他们,则必须通过反射更改您的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM