0

I am designing a system to update member variables in objects automatically by marking them with some annotation. Some other background thread will then update the objects.

To do this, the runtime component doing the updating needs to know all Java objects that contain this annotation. I can see that there are methods to find classes with an annotation type, but going from classes to instances of the classes is a lot harder. I want to avoid explicitly "registering" the object in the constructor, although I could do that as a last resort.

Any suggestions as to how this might be achieved?

rghome
  • 8,529
  • 8
  • 43
  • 62
  • You can have a look at https://stackoverflow.com/questions/1947122/is-there-a-simple-way-of-obtaining-all-object-instances-of-a-specific-class-in-j – Florent Bayle May 15 '17 at 08:26
  • Thanks, but probably all of those methods are are bit to drastic. – rghome May 15 '17 at 11:54
  • 1
    There is no builtin registry for existing objects, hence, you won’t find solution outside the “bit too drastic” category. Finding the objects of a class implies doing what the garbage collector does, traversing all references to find all existing objects. – Holger May 16 '17 at 14:03

1 Answers1

1

You can use some kind of HashMap cache to store objects for update.

1) write annotation @Updatable to mark objects updatable

2) write HashMap that will contain all the objects to update

3) initialize this HashMap on time of app initialization by lookup the objects with @Updatable If you are using Spring that you can write custom BeanPostProcessor for that purposes.

Mike Adamenko
  • 2,944
  • 1
  • 15
  • 28
  • OK - I would prefer a solution that does not require that the object is a Spring bean, but your answer is interesting anyway for that suggestion. Note that for the HashMap (which I have already considered), I think I will need a WeakIdentityHashMap, which unfortunately doesn't exist. – rghome May 15 '17 at 08:57