mercredi 14 septembre 2016

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. The initialization of the object B is in a static block like this:

FilterA implements Filter{ 
  public 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.

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.

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

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 .





Aucun commentaire:

Enregistrer un commentaire