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

后端 未结 8 1842
谎友^
谎友^ 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: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);
    }
    

提交回复
热议问题