I have a logging function that takes the calling object as a parameter. I then call getClass().getSimpleName() on it so that I can easily get the class name to add to my log entry for easy reference. The problem is that when I call my log function from a static method, I can’t pass in “this”. My log function looks something like this:
public static void log(Object o, String msg){
do_log(o.getClass().getSimpleName()+" "+msg);
}
public void do_something(){
log(this, "Some message");
}
But let’s say I want to log from a static function:
public static void do_something_static(){
log(this, "Some message from static");
}
Obviously do_something_static() won’t work because it is static and “this” is not in a static context. How can I get around this? And can I do it without using reflection (since I understand there is a lot of overhead involved and it might affect performance since I log a LOT of data)
I know I can probably hard-code the current class into the call somehow, but I’m sure that when I move the function to another class, I will forget to update the hard-coded reference and it will no longer be correct.
Thanks!
You could add “Class” as first parameter and overload the log method:
Output:
But it feels just bad to have the calling class passed as the first argument. Here’s where object oriented model comes into play as opposite of “procedural” style.
You could get the calling class using the stacktrace, but as you metioned, there would be an overhead if you call it thousands of times.
But if you create is as class variable, then there would be only one instance for class if you happen to have 1,000 classes using this utility, you would have at most 1,000 calls.
Something like this would be better ( subtle variation of this other answer) :
Usage test:
OUtput
Notice the declaration:
That way, it doesn’t matter if you use the “logger” from objectA, objectB, objectC or from a class method ( like main ) they all would have one instance of the logger.