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

后端 未结 8 1822
谎友^
谎友^ 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:39

    You should hard code the class into the call in the short term. If you think you will need this in a variety of places in your project, as it is static, you should encapsulate it and have it take the class as a param.

    public static void do_something_static(Class callingClass){
      log(callingClass, "Some message from static");
    }
    
    0 讨论(0)
  • 2021-02-14 04:42

    Instead of "this" use "MyClass.class" and let your log method treat class objects without getClass().

    But instead of doing this yourself, consider letting the log framework do it.

    0 讨论(0)
提交回复
热议问题