[英]How can I get the instance of a static class which is initiated inside static block in servlet filter?
In my Servlet there is an object B initiated during load time.在我的 Servlet 中有一个对象 B 在加载时启动。 The initialization of the object B is in a static block like this:
对象 B 的初始化在一个静态块中,如下所示:
FilterA implements Filter{
private static B b = new B();
static {b.setText("This is B");}
doFilter(){...}
}
class B{
private String text;
public void setText(String s){
this.text=s;
}
public String getText(){
return this.text;
}
}
where FilterA is a Servlet filter defined in web.xml.其中 FilterA 是 web.xml 中定义的 Servlet 过滤器。
What I am doing is writing a new Servlet filter (filterB) to modify object B. The filterB is placed right after filterA in web.xml as below.我正在做的是编写一个新的 Servlet 过滤器 (filterB) 来修改对象 B。过滤器 B 位于 web.xml 中的过滤器 A 之后,如下所示。
<filter>
<filter-name>filterA</filter-name>
<filter-class>my.FilterA</filter-class>
</filter>
<filter>
<filter-name>filterB</filter-name>
<filter-class>my.FilterB</filter-class>
</filter>
Given that Reflection is the only solution I can use in filter B to retrieve the instance of of class B. Is there any method can be adopted to retrieve it?鉴于反射是我可以在过滤器 B 中使用的唯一解决方案来检索 B 类的实例。有没有什么方法可以检索它?
I don't think Class.forName() is suitable for this case because I am not going to create any new instance of class B but only to retrieve the existing instance .我认为 Class.forName() 不适合这种情况,因为我不打算创建 B 类的任何新实例,而只是检索现有实例。
//new thing goes here //这里有新东西
I am writing a simple test class to simulate the case.我正在编写一个简单的测试类来模拟这种情况。 Please take the following code as the point:
请以以下代码为重点:
package com.jm.test;
public class AIAItest {
private static BB bb = new BB();
static{
bb.setText("sb");
}
public static void main(String[] args){
try {
//TODO use reflection to get the instance of BB, is it possible?
//do not simply refer to bb
} catch (Exception e) {
e.printStackTrace();
}
}
}
class BB{
private String text;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
If you're asking how to code it using reflection, the main points are:如果您要问如何使用反射对其进行编码,要点是:
Like this:像这样:
Field f = AIAItest.class.getField("bb");
f.setAccessible(true); // effectively make it public
BB bb = (BB)f.get(null);
Given that b
is public
and static
in FilterA
, a direct static reference to it should work.鉴于
b
在FilterA
是public
和static
的,对它的直接静态引用应该可以工作。 In FilterB
, this code should work在
FilterB
,此代码应该可以工作
B b = FilterA.b;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.