java 获取当前函数名的实现代码
废话不多说,直接上代码
import java.text.simpledateformat;
import java.util.date;
/**
* java实现类似c/c++中的__file__、__func__、__line__等,主要用于日志等功能中。
*
* @version 1.0
*
*/
public abstract class commonfunction {
/**
* 打印日志时获取当前的程序文件名、行号、方法名 输出格式为:[filename | linenumber | methodname]
*
* @return
*/
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();
}
// 当前文件名
public static string _file_() {
stacktraceelement traceelement = ((new exception()).getstacktrace())[1];
return traceelement.getfilename();
}
// 当前方法名
public static string _func_() {
stacktraceelement traceelement = ((new exception()).getstacktrace())[1];
return traceelement.getmethodname();
}
// 当前行号
public static int _line_() {
stacktraceelement traceelement = ((new exception()).getstacktrace())[1];
return traceelement.getlinenumber();
}
// 当前时间
public static string _time_() {
date now = new date();
simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss.sss");
return sdf.format(now);
}
}