Java: How to get a class object of the current class from a static context?

后端 未结 8 1843
谎友^
谎友^ 2021-02-14 04:10

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 en

相关标签:
8条回答
  • 2021-02-14 04:17

    Well, if you really don't want to hardcode something like ClassName.class, then you can try to infer the class by traversing the stacktrace. Fortunately, someone already did it : ). Also, consider using a logger that allows you to log something without specifying the calling object.

    0 讨论(0)
  • 2021-02-14 04:22

    You could add "Class" as first parameter and overload the log method:

    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 );
        }
    }
    

    Output:

    $ java SomeClass
    SomeClass Hola
    Date Hola
    

    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) :

    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 );
        }
    }
    

    Usage test:

    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");
        }
    }
    

    OUtput

    $ java UsageClass
    (UsageClass) One
    (UsageClass) Two
    (UsageClass) Three
    

    Notice the declaration:

    ....
    class UsageClass {
        // This is invoked only once. When the class is first loaded.
        private static final LogUtility logger = LogUtility.getLogger();
    ....
    

    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.

    0 讨论(0)
  • 2021-02-14 04:22

    Alter method log to:

    public static void log(Class c, String msg){
      do_log(c.getSimpleName()+" "+msg);
    }
    

    and if do_something_static is in class MyClassWithStatics then do_something_static would become:

    public static void do_something_static(){
      log(MyClassWithStatics.class, "Some message from static");
    }
    
    0 讨论(0)
  • 2021-02-14 04:28

    Replace your static functions with non-static ones. Instead of

    Utils.do_something(...)
    

    do

    new Utils().do_something(...)
    
    0 讨论(0)
  • 2021-02-14 04:30

    querying the stacktrace maybe worty for your problem. You have 3 possible approachs.

    Exception#getStackTrace()

    Just create an exception instance and get the first frame:

    static String className() {
        return new RuntimeException().getStackTrace()[0].getClassName();
    }
    

    Thread

    Using Thread is even easier:

    static String className2() {
        return Thread.currentThread().getStackTrace()[1].getClassName();
    }
    

    these two approachs have the disadvantage that you cannot reuse them. So you may want to define an Helper class for that:

    class Helper {
    
        public static String getClassName() {
            return Thread.currentThread().getStackTrace()[2].getClassName();
        }
    } 
    

    now you can obtain your class name programmatically, without hardcoding the class name:

    public static void log(Object o, String msg){
        do_log(Helper.getCClassName() + "  " + msg);
    }
    
    0 讨论(0)
  • 2021-02-14 04:35

    Wouldn't implementing some sort of Singleton do what you need?

    public class LogUtility {
    
        private final String loggingFrom;
        private static LogUtility instance;
    
        public static LogUtility getLogger() {
            if(instance == null)
                this.instance = new LogUtility();
            StackTraceElement [] s = new RuntimeException().getStackTrace();
            this.instance.setLoggingFrom(s[1].getClassName())
            return this.instance;
        }
    
        private LogUtility() {}
    
        private void setLoggingFrom(String loggingClassName){
            this.loggingFrom = loggingClassName;
        }
    
        public void log( String message ) {
            System.out.println( loggingFrom + message );
        }
    }
    

    Usage (anywhere in your project):

    LogUtility.getLogger().log("Message");
    
    0 讨论(0)
提交回复
热议问题