As we all know, in C language, we can obtain file name and line number through macros FILE and __LINE__ , and in Java language, we can obtain file name, class name, method name, and line number through StackTraceElement class. The specific code is as follows:
public static int getLineNumber( ){ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); return stackTrace[1].getLineNumber( );}public static String getMethodName( ){ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); return stackTrace[1].getMethodName( );}public static String getFileName( ){ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); return stackTrace[1].getFileName( );}public static String getClassName( ){ StackTraceElement[] stackTrace = new Throwable().getStackTrace(); return stackTrace[1].getClassName();}The above is all about using Java to obtain file names, class names, method names and line numbers. I hope the content of this article will be helpful to everyone in learning Java.