0

I'm trying to execute the same code in every subclass of a class once the class is loaded. I need to scan the classes fields using reflection to generate an outline of the data container/class.

Is there any way to do this without invoking a method of the superclass in every subclass once it is initialized? (e.g. inheriting the static initializer of the super class)

EDIT: I'm writing a library that manages some data objects. When I want to store more data in them, I'd usually subclass them. But as this get's pretty annoying when handing them back to the library and having to cast, check instanceof all the time, I wanted to create a system of "data components", that could be added to this data objects. I want to be able to use these data components in code by directly accessing their members (not via id or string), serialize them and let the user edit them in a dynamic GUI. For generating the GUI (and for serializing) I need to know the fields of the "data component classes", that were handed to my library, but I don't want to force the main application to make a library call to register each new data component class. Therefore I'm asking if it's possible to do this automatically for each subclass of a given "data component" class, that is loaded. (without classpath scanning)

Another solution would be to just declare a getFields() method in the data component superclass which automatically scans/registers the subclass when needed, but this would add some delay (i don't know how fast/slow reflection is) on the first call when the application is not in init anymore and therefore should be running as fast as possible. (I'd like to do the scanning beforehand)

Geosearchef
  • 600
  • 1
  • 5
  • 22
  • Unless you're doing something funky with class loaders, the static initializer of the super class should only be called once. – Joe C Mar 26 '17 at 16:00
  • What is you *business problem* you want to solve? There might be more straight forward solutions for what you want to accomplish. So please share what your goal is. – Timothy Truckle Mar 26 '17 at 16:09
  • Question edited to explain problem in detail. – Geosearchef Mar 26 '17 at 16:26
  • Anything that requires a supertype to have knowledge of its subtypes is a bad solution. Anything that requires a supertype to have knowledge of _all_ of its subtypes is a meltdown waiting to happen. If a type needs to be "registered​", the type should register itself, not depend on the supertype to somehow magically know of the subtype. None of this happens during class loading; it happens during class initialization. – Lew Bloch Mar 26 '17 at 17:57
  • My problem is not about the super type knowing about subtypes, it's about automatically executing the same code during class initialization in every subtype. (without duplicate code) – Geosearchef Mar 26 '17 at 21:34

0 Answers0