0

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.

Parzavil
  • 388
  • 3
  • 13

1 Answers1

2

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
Snix
  • 541
  • 4
  • 12
  • This does look a lot nicer but sadly I am stuck using Java 8 since it will need to run on Windows XP. – Parzavil Jun 04 '20 at 12:25