0

I use a superclass which stores references to all instances of SuperClass and various subclasses.

public class SuperClass{
  private static final Map<Integer,? extends SuperClass> instances=new TreeMap<>();
  private static final SuperClass inst1=new SuperClass(1,"1");
  public final int ref; // exemplary comparable property
  private final Object commonAttribute; //exemplary
  protected SuperClass(Object o,int ref){
    commonAttribute=o;
    this.ref=ref;
    instances.put(ref,this);
  }
}

When I instantiate variables of the subclasses, I expect all instances to be added to instances.

public class SubClass{
  private final Object specificAttr;
  private static final SubClass inst2=new SubClass(2,"2","whatever");
  private final SubClass(Integer i,Object o1, Object o2){
     super(i,o1);
     this.specificAttribute=o2;
  }
}

Confusingly the elements of instances seem to depend on in which class main method in. When I have the main method in the Superclass, only inst1 is added, which is not desired in my case. Is there any mechanism to customize which (static!) variables are initialised by jvm.

SantiBailors
  • 1,596
  • 3
  • 21
  • 44
AnD
  • 1
  • 1
  • jvm instantiates static variables when class is loaded. more info here http://stackoverflow.com/questions/3499214/when-does-static-class-initialization-happen. just do something from the list with both classes – AdamSkywalker Nov 24 '15 at 11:25

2 Answers2

0

There is no way for a super class to know what classes extend it, except by scanning the whole classpath and loading the classes.

cadrian
  • 7,332
  • 2
  • 33
  • 42
0

It's because when your main method is in the super class, the JVM has no need of sub class which is not referenced anywhere, so JVM doesn't load it and doesn't instantiate static fields.

You can check all classpaths to force loading of expected classes or have a class (referenced in main class by example) with a static block which manually references all wanted subclasses. By doing this, all subclasses should be loaded at runtime but you loose the benefit of auto-registered subclasses.

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Prim
  • 2,880
  • 2
  • 15
  • 29