static イニシャライズ

static イニシャライズのコードは組むことは少ないが、
自クラスのメソッドMap を用意すると応用がありそうだ。

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class Foo{
   private String color;
   private static Map<String,Method> amap;

   static{
      amap = new HashMap<String,Method>();
      try{
      amap.put("a",Foo.class.getDeclaredMethod("fooA",int.class));
      amap.put("b",Foo.class.getDeclaredMethod("fooB",int.class));
      amap.put("c",Foo.class.getDeclaredMethod("fooC",int.class));

      System.out.println("static init!!");
      }catch(Exception e){
      }
   }


   public Foo(String color){
      this.color = color;
      System.out.println("Constructor!!");
   }

   public void exec(String key,int size){
      try{
      Method method = amap.get(key);
      method.invoke(this,size);

      }catch(Exception e){
         e.printStackTrace();
      }
   }
   private void fooA(int size){
      System.out.println("Foo fooA() : "+this.color+"  size = "+size);
   }
   private void fooB(int size){
      System.out.println("Foo fooB() : "+this.color+"  size = "+size);
   }
   private void fooC(int size){
      System.out.println("Foo fooC() : "+this.color+"  size = "+size);
   }

}
-----------------------------------
実行、以下の様に2個のインスタンス生成で実行すると、、

  Foo f = new Foo("Red");
  f.exec("a",100);
  f.exec("b",120);
  f.exec("c",160);

  Foo f2 = new Foo("Blue");
  f2.exec("a",200);
  f2.exec("b",220);
  f2.exec("c",260);

結果は、、、

static init!!
Constructor!!
Foo fooA() : Red  size = 100
Foo fooB() : Red  size = 120
Foo fooC() : Red  size = 160
Constructor!!
Foo fooA() : Blue  size = 200
Foo fooB() : Blue  size = 220
Foo fooC() : Blue  size = 260