1

I have to write a method which can be called in any class to get the name of the class which is calling the method. The return type should be Class, so I can use it for another method. So that is what I have right now, but I think its not a clean code. Maybe there is way to use

public class Vlogger{
    public static Class getInstance() throws ClassNotFoundException {
       String className =new Exception().getStackTrace()[1].getClassName();
       return Class.forName(className);
    }
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
TheLegend31
  • 51
  • 2
  • 11
  • 2
    Possible duplicate of [Get current stack trace in Java](http://stackoverflow.com/questions/1069066/get-current-stack-trace-in-java) – Fildor Mar 09 '17 at 08:55
  • 1
    [I´m gonna quote the accepted answer:](http://stackoverflow.com/questions/1696551/how-to-get-the-name-of-the-calling-class-in-java) "But in real there should be no need for this, unless for some logging purposes, because this is a fairly expensive task. What is it, the problem for which you think that this is the solution? We may come up with -much- better suggestions.". – SomeJavaGuy Mar 09 '17 at 08:58
  • Yes youre right I need to code a logging Class, with use A log class and a class wich builds the logs for the sysout – TheLegend31 Mar 09 '17 at 09:00
  • Why reinvent the wheel? You can use log4j or slf4j/logback, slf4j/log4j , ... – Fildor Mar 09 '17 at 09:02
  • I already use these: org.slf4j.LoggerFactory; and org.slf4j.Logger – TheLegend31 Mar 09 '17 at 09:04
  • What do you need the stacktrace for, then? Do you want to log the caller of a (or some) specific method? – Fildor Mar 09 '17 at 09:08
  • so when I am Using the current Logger I do it like that: – TheLegend31 Mar 09 '17 at 09:10
  • private static Logger LOG = LoggerFactory.getLogger(ResourceStatements.class); – TheLegend31 Mar 09 '17 at 09:10
  • now I want to code a Class , wich do this and prepare the finish sysout statements. – TheLegend31 Mar 09 '17 at 09:11

1 Answers1

1

Unfortunately, there is no clean code for this task yet.

Be prepared to replace it, when Java 9 has been released:

public class Vlogger{
    public static Class getInstance() {
       return StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
                         .getCallerClass();
    }
}
Holger
  • 285,553
  • 42
  • 434
  • 765