I am wondering if it is possible for a developer to write a class so that when some other developer instantiates an object of the aforementioned class, a call on a specific method of the class gets added to his code.
Let me be more specific. Let's say that I create a class named A
with the following structure:
public class A {
public A() {
// Some instantiations
}
// Code class
// Method that always should be added
public void method() {
// Code
}
}
I wrap this class into a package and some other developer instantiates class A
in a new object. When he does that, a call on method()
is added right after the instantiation, probably with a comment right above it:
// Code
A myA = new A();
// Do some operations on A
// You should always wrap up with a call on method
myA.method();
// Code
This is just to inform the developer not to forget to call it at a specific place in his code.
The reason I am asking this is because I have created a class that contains a queuing mechanism that will be used in a large project as also as in future projects. I need to force every future developer to reference a method called close()
at the end of his code, to terminate the connection to the queuing system. If he forgets to do that (and there is very high possibility that he/she does that), the connections will be open, adding a huge overhead to the total project.
If there is no way to implement this (and to my knowledge, I can't think of anything), what's the logic behind to not include something like this in standard JDK by Oracle? I can think of examples of JDK's own libraries that could be benefited by this (e.g. closing a PrintWriter
when you are finished writing to a file), so I don't think that this is a misunderstanding from my side of Java's principles.
UPDATE
Because I think I accidentally started a flame war...
I do think that a good API is written in a way that does procedures like this automatically. Instantiate an object/call a method and the rest are done automatically. But for my case, I need something like C++'s destructors: a way to force or otherways warn the developer to close the connection to the queuing system he created.
UPDATE 2
The project is unfortunately written in JDK 7 that does not support lambda functions.
UPDATE 3
As it turns out my assumption was true and there is no standard Java feature (except maybe of the lambda functions) that can be leveraged. Can I add at least a warning on the other developer's class that he forgot to close the connection?