简体   繁体   English

在 static 子 class 中获取调用父 class

[英]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.是否可以在 class 中使用 static 方法,获取调用 class 的名称。 I would like to be able to use this in a static class currently used to make logs.我希望能够在当前用于制作日志的 static class 中使用它。

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.我想知道我是否可以访问 class 的名称而无需在方法中传递它。

I do not suggest the answer provided by TreffnonX because this is a fairly expensive task and it may slow down the application itself .我不建议使用 TreffnonX 提供的答案,因为这是一项相当昂贵的任务,并且可能会减慢应用程序本身的速度 Source 资源

Instead you can use the new Stack Walking API ( Javadoc ) available since Java 9.相反,您可以使用自 Java 9 起可用的新Stack Walking API ( Javadoc )。
It provides an efficient standard API for stack walking that allows easy filtering of, and lazy access to, the information in stack traces.它为堆栈遍历提供了一个高效的标准 API,允许轻松过滤和延迟访问堆栈跟踪中的信息。

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这是 output

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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