简体   繁体   中英

Get the calling parent class in a static child class

Is it possible for a static method in a class, get the name of the calling class. I would like to be able to use this in a static class currently used to make logs.

public class Log {

    static void log(Class a, String b){
        System.out.print("[" + time() + "|" + a.getName() + "]" + " " + b);
    }
    static void logLine(Class a, String b){
        System.out.println("[" + time() + "|" + a.getName() + "]" + " " + b);
    }
    static void log(Class a, String[] b){
        for(int c = 0; c < b.length; c++){
            Log.logLine(a, b[c]);
        }
    }
    static String time(){
        return "" + java.time.LocalTime.now();
    }

}

I would like to know if I can access the name of the class without needing to pass it in the method.

I do not suggest the answer provided by TreffnonX because this is a fairly expensive task and it may slow down the application itself . Source

Instead you can use the new Stack Walking API ( Javadoc ) available since Java 9.
It provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces.

Here is an example

import static java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE;

class Log {

    public static void main(String ...args){
        new SomeObject().execute();
    }

    static void log(String b){

        StackWalker walker = StackWalker.getInstance(RETAIN_CLASS_REFERENCE);

        Class<?> callerClass = walker.getCallerClass();

        System.out.print("[" + time() + "|" + callerClass.getName() + "]" + " " + b);
    }

    static String time(){
        return "" + java.time.LocalTime.now();
    }

}

class SomeObject {

    public void execute(){
        Log.log("I'm doing something");
    }

}

Here is the output

[12:13:17.146856|SomeObject] I'm doing something

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM