title: how to parameterize static fields in Java generics based on type
body: <p>As far as I can tell, static fields in Java generics are shared among all instances regardless of the type parameter. For example, in the following class</p>
  
  <pre><code>class A&lt;T&gt; {
      static String s;
  }
  </code></pre>
  
  <p>String s will be shared among all instances of A regardless of T.</p>
  
  <p>I would like to parameterize the static field (and related one-time operations) on T, so that, in the above example, the String s would be separate in instances of A&lt; Integer >, A&lt; Double >, and so on.</p>
  
  <p>So far, I was able to come up with the following solution:</p>
  
  <pre><code>static class Rec {
      private Class&lt;?&gt; clazz;
      private String name;
  
      public Rec(Class&lt;?&gt; clazz, String name) {
          this.clazz = clazz;
          // parameterized, quasi-static field
          this.name = name;
      }
  
      protected Class&lt;?&gt; ofClass() { return clazz; }
      protected String ofName() { return name; }
  }
  
  static abstract class Base&lt;T&gt; {
      private static List&lt;Rec&gt; derived = new ArrayList&lt;Rec&gt;();
      private Class&lt;T&gt; type;
  
      public Base(Class&lt;T&gt; type, String s) {
          this.type = type;
          for (Rec rec : derived) {
              if (rec.ofClass() == type) return;
          }
          Rec rec = new Rec(type, type.getName());
          derived.add(rec);
          System.out.println("Added " + rec.ofName());
      }
  
      protected String getName() {
          for (Rec rec : derived)
              if (rec.ofClass() == this.type) return rec.ofName();
          return null;
      }
  }
  
  static class Test1 extends Base&lt;Test1&gt; {
      public Test1() {
          super(Test1.class, Test1.class.getName());
      }
  }
  
  static class Test2 extends Base&lt;Test2&gt; {
      public Test2() {
          super(Test2.class, Test2.class.getName());
      }
  }
  
  Test1 t1 = new Test1();
  System.out.println(t1.getName());
  
  Test2 t2 = new Test2();
  System.out.println(t2.getName());
  
  Test2 t3 = new Test2();
  System.out.println(t3.getName());
  </code></pre>
  
  <p>This code creates separate instances of the quasi-static field in a list of per-derived-type records in the base class. Hence two separate class names "Test1" and "Test2" are printed to the console; however, the t2 and t3 instances share the same name field.</p>
  
  <p>Although the base class is not aware of its derived classes at compile time, it is at runtime, which is perhaps is not as clean as it should be. In addition, there is a linear search of the list to find a corresponding type every time a base method using a parameterized quasi-static field is invoked.</p>
  
  <p>Is there a more efficient, idiomatic way of doing that?</p>