Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You could add "Class" as first parameter and overload the log method:</p> <pre><code>public class SomeClass { // Usage test: public static void main( String [] args ) { log( SomeClass.class, "Hola" ); log( new java.util.Date(), "Hola" ); } // Object version would call Class method... public static void log( Object o , String msg ) { log( o.getClass(), msg ); } public static void log( Class c , String message ) { System.out.println( c.getSimpleName() + " " + message ); } } </code></pre> <p>Output:</p> <pre><code>$ java SomeClass SomeClass Hola Date Hola </code></pre> <p>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.</p> <p>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. </p> <p><strong>But</strong> 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. </p> <p>Something like this would be better ( subtle variation of this <a href="https://stackoverflow.com/questions/1075935/using-current-class-in-java-static-method-declaration/1076166#1076166">other</a> answer) :</p> <pre><code>public class LogUtility { private final String loggingFrom; public static LogUtility getLogger() { StackTraceElement [] s = new RuntimeException().getStackTrace(); return new LogUtility( s[1].getClassName() ); } private LogUtility( String loggingClassName ) { this.loggingFrom = "("+loggingClassName+") "; } public void log( String message ) { System.out.println( loggingFrom + message ); } } </code></pre> <p>Usage test: </p> <pre><code>class UsageClass { private static final LogUtility logger = LogUtility.getLogger(); public static void main( String [] args ) { UsageClass usageClass = new UsageClass(); usageClass.methodOne(); usageClass.methodTwo(); usageClass.methodThree(); } private void methodOne() { logger.log("One"); } private void methodTwo() { logger.log("Two"); } private void methodThree() { logger.log("Three"); } } </code></pre> <p>OUtput</p> <pre><code>$ java UsageClass (UsageClass) One (UsageClass) Two (UsageClass) Three </code></pre> <p>Notice the declaration:</p> <pre><code>.... class UsageClass { // This is invoked only once. When the class is first loaded. private static final LogUtility logger = LogUtility.getLogger(); .... </code></pre> <p>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. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload