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)
Related
I use in my project a lib with some class with a lot of static field and other stuffs, who are indirectly updated and consulted at runtime in my app.
I can't update or ignore or mock this class.
How can I re-execute the method who initialise the static field of a class?
I'm currently writing test in my app, which trigger this class.
I want the static field of this class to be at their init state each time I start my app.
The issue is, setting manualy those static field is not possible, it would be too complexe. I need them to be put at their initial state "automaticaly"
I can't change anything to the code of the class, because it's in a lib.
Any idea how I can do that? With reflexion, maybe?
If resetting static fields manually are too complex and classes are stateless, one of the way could be to use custom class loader and reload your classes whenever required.
This article may provide some idea about loading and reloading classes.
You should watch out for performance hit.
I have a class GuiApplication and a class ImageHandler. The GUI can work with the ImageHandler (and thus images) trough a class called Crawler which provides a façade for the methods the GUI can use.
There's a separate class called StartUp which has a main method and the only thing done there is create an instance of GuiApplication (so basically it starts the program).
In my GUI, there is a JTextPane which serves as a logger: certain actions and events will be shown there. With output that comes from elsewhere within my GUI, I can easily update its value. However, when there is output that comes from within my domain classes, e.g. ImageHandler, I can't do anything.
There is a Try-Catch block which prevents my program from crashing when an unexpected image URL passes trough my reader, and when it does I would like to show this in the textpane ("Error: File xxx could not be read").
However, I don't see an elegant way to communicate this to my GUI: I can't create an instance because that would create a new GUI and I don't think approaching my GUI trough the StartUp file is good practice either.
I was considering defining the variable in a different class that could be accessed troughout the entire project, but I wanted some opinions first.
The practical way is to throw a RuntimeException, which does not need to change the methods' signature. Catch it in the GUI and do a JOptionPane.showMessageDialog.
The other way is to extend the API of ImageHandler with an event handler, and install a message handler that calls in GuiApplication JOptionPane.showMessageDialog.
One option that comes to mind is a callback: pass an instance (it can be an anonymous class) of some interface to the method doing the work, which it calls when an error occurs.
I have a manager class that is responsible for managing Objects of a certain kind. To do so it needs to manipulate these Objects, but these Objects have no relation to the manager whatsoever, so design technically, they are in separate packages "project.managers" and "project.objects" . The important thing is that the Objects in question should only be manipulated by the managers and nowhere else, but need to be accessible by every other class in the project.
As such I'd like to have the managers have access to manipulating methods, but restrict access to every other class. The most obvious one would be to move the manager class and object class into the same package and declare manipulating methods protected, but as the managers and objects are completely separate entities they don't fit there philosophically.
(This is partly because I want my IDE to stop showing me the manipulating methods whenever I autocomplete code on the Objects in question so I always have to go the route through the manager so corresponding tables are correctly updated whenever I change the Objects in question).
Are there any ideas to that or is the obvious way the best in any case?
Why not have an interface called
ManagerFunctions
and another called
ClientFunctions
You managed objects will implement both of these.
When you create the managed objects, you pass them around, but only as references to ClientFunctions. The manager objects will, however, refer to them as ManagerFunctions and consequently have access to their 'managed' functions. The appropriate casting will simply expose the appropriate methods.
Your IDE will automatically present you wil the appropriate methods depending on how these objects are referenced.
You're asking for something akin to the "friend" declarations of C++, but there's no direct equivalent in Java - package visibility is the nearest. Alternatively you could go for a model like the XML DOM, where the methods that should be public are defined in interfaces and all client access is via these interfaces. The manager would know the concrete class of the implementation so could downcast to that as required.
As such I'd like to have the managers have access to manipulating methods, but restrict access to every other class. The most obvious one would be to move the manager class and object class into the same package and declare manipulating methods protected...
Technically, you would declare the manipulating methods package protected (no modifier at all). Protected methods allow the class to be extended easier.
but as the managers and objects are completly seperate entities they don't fit there philosophically.
I understand. Java doesn't have the "friend" declaration that C++ has.
You could comment the manipulating methods, but that doesn't solve your Eclipse problem.
I have a JPanel that handles a bunch of settings that I would like to save and load by file name.
It seems natural that since the panel already exists and knows all about itself that the load and save should be handled by the panel itself through a Save(String filename) and Load(String filename) actions attached to buttons.
However all the serialization and/or persistence examples I find require an external overseer that passes the object into the serializer functions.
Can I simply serialize the panel object using something similar to writeObject(this) and this=readObject() or is there a standard way to do this that I haven't searched properly for?
I am not sure I understand the question entirely but all the serialization logic definitely resides in the Object methods (readObject and writeObject).
When talking about who would invoke those methods, it all depends on your use case. There are several reasons for serializing an object, like for ex: if one wants to pass the object across the wire to another JVM, or you want to persist the state of the object between JVM restarts, or any other use case where the entire state of the Object needs to be saved outside of the JVM its running in.
In your use case, can it be done? yes. Is that a good practice, maybe not. An abstraction is better because what if you have a need to persist other objects not accessible to JPanel? What if there is a need perform some other logic before serializing an object? What if there is a need for ordering or some other requirement that cannot be handle by your JPanel?
You can learn more about Java Serialization here
Say I have a class with a few fields all marked with a custom annotation. In my case it is #inject, because this is being used for dependency injection. How can I run a method in a separate class each time that annotation is used in my a class? In other words, each time a class is loaded the annotation runs a method that will collect the field data and in turn set the field.
I already have the entire system set up for collecting the resources, but I need some direction on how to actually run that code when the class with #inject annotation is loaded. Is this something that can be done by defining some sort of method in the annotation interface that performs the data collection?
My initial thought is to use a custom class loader, but I don't want to have to set the class loader when I use this jar in other projects. Is there a way to set a custom class loader programmatically for specific classes at runtime? I'm already doing a lot of pre-runtime reflection stuff and i'll already know which classes need to be loaded with a custom loader. Its just a matter of not knowing or if its even possible to set a custom loader on a class from within the code.
Can a classloader even be used to perform tasks such as pre-populating fields, or am I running off on a wrong tangent here? I just need a little direction on the most common way this type of thing is done (pre-populating class fields at runtime).
I was overthinking this problem. You cannot actually run code automatically prior to loading a class (unless its a servlet filter etc). In my situation the answer was to create an instance based on a specific class that already held the resource data I needed. Similar to how Google's Guice does it.
See this question for more insight: How does Guice Populate Annotated Fields
You can use injectors from Google Guice or Spring Framework.