应用服务器如何注入私有字段? [英] How do app servers inject into private fields?
问题描述
我看到了这个问题
关于如何手动注入带注释的私有字段(方式是添加setter或通过构造函数)
about how to manually inject into annotated private fields (The way is adding setters or through a constructor)
但是,重点是应用服务器(如 glassfish、axis2、jboss 等)如何运行能够注入最终的私有字段(无需添加 setter 或构造函数到用户类)?
But, the point is how do an application server (like glassfish, axis2, jboss, ...) is able to inject into a final private field (without adding setters or constructors to the user class)?
引用引用的问题:
public SomeClass {
@Inject
private SomeResource resource;
}
他们是否使用允许访问私有字段的自定义 JVM(不是标准的)?
Do they use a customized JVM (not the standard one) that allows to access private fields?
谢谢
推荐答案
这是一个简单的反射技巧".它依赖于 Field.setAccessible()
方法强制成员以编程方式访问:
It's a simple reflection "trick". It relies on the Field.setAccessible()
method to force the member to be accessible programmatically:
为此设置可访问标志对象到指示的布尔值.值为 true 表示反射对象应该抑制 Java语言访问检查何时用过的.值为 false 表示反射的对象应该强制执行Java 语言访问检查.
Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.
Reflection API 用于获取该字段的句柄,调用setAccessible()
,然后可以通过注入框架进行设置.
The Reflection API is used to get a handle on the field, setAccessible()
is called, and then it can be set by the injection framework.
看一个例子 此处.
没有魔法,没有自定义虚拟机.
No magic, no custom VM.
这篇关于应用服务器如何注入私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!