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

后端 未结 8 1869
谎友^
谎友^ 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条回答
  •  旧时难觅i
    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");
    

提交回复
热议问题