如何应用服务器注入到私人领域? [英] How do app servers inject into private fields?
问题描述
我看到了这个问题。
<一个href=\"http://stackoverflow.com/questions/2021716/inject-into-private-package-or-public-field-or-provide-a-setter\">http://stackoverflow.com/questions/2021716/inject-into-private-package-or-public-field-or-provide-a-setter
有关如何手动注入注解私有字段(该方法是将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?
感谢
推荐答案
这是一个简单的反射绝招。它依赖于<一个href=\"http://java.sun.com/javase/6/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible%28boolean%29\"相对=nofollow> Field.setAccessible()
方法强制会员可访问编程方式:
It's a simple reflection "trick". It relies on the Field.setAccessible()
method to force the member to be accessible programmatically:
设置此accessible标志
对象指示的布尔值。
true值指示
反射的对象应该要喝preSS的Java
语言访问检查时,它是
用过的。假值表示
反射的对象应该实施
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.
反射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.
查看示例<一个href=\"https://web.archive.org/web/20080511181935/http://radio.javaranch.com/val/2004/05/18/1084891793000.html\"相对=nofollow>这里。
没有魔法,没有自定义虚拟机。
No magic, no custom VM.
这篇关于如何应用服务器注入到私人领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!