dimanche 29 novembre 2015

java - limitation of static methods and newInstance() introspection - any workaround?

So, I'm working on a custom logging/audit module for some of our java spring back-ends.

This module is used to fire all sorts of custom events that are saved to a database for later retrieval/reporting.

  • "User2 registered"
  • "User5 bought productX"
  • "MoonLanding occurred with UserN, UserB"

all sorts of events really. each event has an event_type and an event_category and a wide variety of varying parameters.

There is a big hierarchy of EventBuilder classes which allow building all those custom events that end up in the exact same database table (using one single associate JPA Entity). Each of those EventBuilder has a different constructor that takes different parameters relevant to that "custom event record" we are trying to build.

Now the Problem is as follow: All EventBuilder have the 2 following method: getEventType() and getEventCategory() which are sort of meta static methods but are not declared as such. The only reason they are not declared as static is so that some introspection/reflection code can find all the EventBuilder classes, instantiate them using newInstance(), assume those 2 methods will be there (as part of an Interface always implemented) and build a list of all possible event_types, event_categories and how they relate to each other.

The problem with this is that is required those EventBuilder classes to have a default constructor so that those 2 methods can be queried and that info retrieved without having to use the real custom constructors of those object. It works but it introduces the possibility to have EventBuilder instance not initialised properly.

It seems that the 2 available options are massively flawed:

  • current solution of bad default constructor (so that all those classes can be instantiated in a generic way) and 2 static methods not declared as static (so that they can be overridden in the class hierarchy)
  • making the 2 methods static but now they can't be part of a java interface, they can't be overridden in the class hierarchy, the introspection/reflection code can't assume they will be there, etc.

Has anyone got a better third idea? Many Thanks!





Aucun commentaire:

Enregistrer un commentaire