Reputation: 1407
in my project I have a set of classes (whose names and number I don't apriori) which I want to add a public static method to.
For simplicity, let assume that I want to add a static method which returns the static logger instance of the class. The only requirement is that the static function should be called as follows:
public class Foo {
private static final Logger LOG = LoggerFactor.getLogger(Foo.class);
public static void main(String[] args) {
Foo.getLogger().info("works!");
}
}
Since I think this a cross cutting concern I think solving my issue with AspectJ here, but I didn't find any information about my scenario.
My questions are:
I'm aware of the possibility of dyamically declare the parent of my classes implementing an interface, but then I'm stuck because I cannot generate static methods on interface:
public aspect StaticMethodAspect {
public interface HasStaticMethod {}
declare parents: ... implements HasStaticMethod;
public static Logger HasStaticMethod.getLogger() { //aspect error
...
}
}
And I'm also aware of this solution, but it doesn't meet my requirement about the way of call the method.
Thanks for any kind reply
Upvotes: 0
Views: 95
Reputation: 67297
If you want to declare static methods or members via ITD you need to know the class name, which is not the case for you. So you are stuck with doing things similar to what you already found, see also my answers here:
These examples also show how to log directly from another aspect because usually logging is also a cross-cutting concern. So if you can avoid logging manually, just use my approach.
But if you definitely do want to have a static logger for each target class and indeed use it the way your sample code shows, use the AspectJ integration with annotation processing briefly described and linked to from my first answer on the above list. Feel free to ask follow-up questions in case you do not understand the sample code from both links I provided there.
Upvotes: 1