Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the java file/line number?

Tags:

java

In C/C++ the filename is returned by FILE and line number is returned by LINE. Java does have a getFileName(), but does not seem to have a corresponding getLineNumber(). It would be nice to be able to do something like this:

catch (Exception e) {
    System.err.println(this.getFileName() + this.getLineNumber() + e.getMessage());
}

Is there a way to get the java file/line number?

like image 441
jacknad Avatar asked Sep 08 '10 15:09

jacknad


2 Answers

public static void main(String[] args)
{
    StackTraceElement frame = new Exception().getStackTrace()[0];
    System.out.println(frame.getFileName());
    System.out.println(frame.getLineNumber());
}
like image 71
gawi Avatar answered Oct 02 '22 17:10

gawi


Use this:

http://download.oracle.com/javase/1.4.2/docs/api/java/lang/StackTraceElement.html

like image 42
gpeche Avatar answered Oct 02 '22 17:10

gpeche