Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何获取在servlet过滤器的静态块中启动的静态类的实例?_Java_Servlets_Reflection - Fatal编程技术网

Java 如何获取在servlet过滤器的静态块中启动的静态类的实例?

Java 如何获取在servlet过滤器的静态块中启动的静态类的实例?,java,servlets,reflection,Java,Servlets,Reflection,在我的Servlet中,有一个在加载期间启动的对象B。对象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;

在我的Servlet中,有一个在加载期间启动的对象B。对象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;
   }
 }
其中FilterA是web.xml中定义的Servlet过滤器

我正在做的是编写一个新的Servlet过滤器(filterB)来修改对象B。filterB位于web.xml中filterA的后面,如下所示

<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>

鉴于
b
FilterA
中是
public
static
,对它的直接静态引用应该有效。在
FilterB
中,此代码应该有效

B b = FilterA.b;

如果您询问如何使用反射对其进行编码,那么要点如下:

  • 对于静态字段,Field.get()方法不需要实例
  • 你必须公开这个领域
像这样:

Field f = AIAItest.class.getField("bb");
f.setAccessible(true); // effectively make it public
BB bb = (BB)f.get(null);

我不太熟悉java servlet,但是你应该能够通过FilterA.B访问B类。你能修改FilterA的源代码吗?不太可能,因为FilterA是内置在JAR中的,由第三方提供的…如果这不是你在该过滤器中需要的唯一修改,你可以期待修改第三方编译的字节码,而不是通过Reflection.thx为你修改它先回答。这是我的错误写它公开,它实际上应该是私人的。这就是为什么我在思考反思的解决方案。
Field f = AIAItest.class.getField("bb");
f.setAccessible(true); // effectively make it public
BB bb = (BB)f.get(null);