Java gets the implementation code for the current function name
- 2020-04-01 02:13:43
- OfStack
Without further ado, go straight to the code
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Java Achieve similar C/C++ In the __FILE__ , __FUNC__ , __LINE__ Etc. , Mainly used for logging and other functions.
*
* @version 1.0
*
*/
public abstract class CommonFunction {
public static String getFileLineMethod() {
StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
StringBuffer toStringBuffer = new StringBuffer("[").append(
traceElement.getFileName()).append(" | ").append(
traceElement.getLineNumber()).append(" | ").append(
traceElement.getMethodName()).append("]");
return toStringBuffer.toString();
}
//Current file name
public static String _FILE_() {
StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
return traceElement.getFileName();
}
//Current method name
public static String _FUNC_() {
StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
return traceElement.getMethodName();
}
//The current line number
public static int _LINE_() {
StackTraceElement traceElement = ((new Exception()).getStackTrace())[1];
return traceElement.getLineNumber();
}
//The current time
public static String _TIME_() {
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return sdf.format(now);
}
}