Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get source file-name/line-number from a java.lang.Class object

Is it possible, given a java.lang.Class object, to get the source file name and the line number at which the class was declared?

The data should be available in the .class file's debug info. The only place I know of, where the JDK returns such debug info is in java.lang.StackTraceElement but I'm not sure if it's possible to force Java to create a java.lang.StackTraceElement instance for an arbitrary class, because we are not executing a method in the class.

My exact use case is an anonymous inner class which has a compiler generated name. I want to know the file name and the line number for the class declaration.

I prefer not to use a byte-code manipulation framework, but I can fall back to it if I have to.

like image 208
Saintali Avatar asked Sep 20 '11 10:09

Saintali


People also ask

What is the name of the source file in Java?

The source code file has file extension ". java". This is the file that is converted into the Java bytecode file, also called the class file.

Can we save a Java source file by name than the class name?

Yes,it is possible to compile a java source file with different file name but you need to make sure none of the classes defined inside are public... when you compile the source file the corresponding . class files for the classes inside the source file are created.

Is java file name a valid source file name?

java file is a perfectly valid source file.

Where is the source file in Java?

A typical location is at the top of the source tree. Oracle Solaris, Linux, and macOS: For example, if the source files for the java. math package are contained in the /home/user/src/java/math directory, then you could create an overview comment file in /home/user/src/overview.


2 Answers

The answer to this comes down to how much control you have over the code that is implementing the Listener. You are right that it is not possible to create a stacktrace without being in a method.

The general technique is to create an Exception(), in the constructor, but don't throw it. This contains the stacktrace information, which you can use how you want. This will give you the line number of the constructor, but not of the class. Please note that this method is not particularly performant either, because creating a stacktrace is expensive.

You will need to either:

  1. force some code to be executed in the constructor (relatively easy if your Listener is an abstract class which you control)
  2. Instrument the code somehow (the cure seems worse than the disease here).
  3. Make some assumptions about the way classes are named.
  4. Read the jar (do the same thing as javac -p)

For 1), you'd simply put the Exception creation in the abstract class, and the constructor gets called by the subclass:

class Top {
    Top() {
        new Exception().printStackTrace(System.out);
    }
}

class Bottom extends Top {
    public static void main(String[] args) {
        new Bottom();
    }
}

this produces something like:

java.lang.Exception
    at uk.co.farwell.stackoverflow.Top.<init>(Top.java:4)
    at uk.co.farwell.stackoverflow.Bottom.<init>(Bottom.java: 11)
    at uk.co.farwell.stackoverflow.Bottom.main(Bottom.java: 18)

In general, there are some naming rules which are followed: If you have an outer class called Actor and an inner called Consumer, then the compiled class will be called Actor$Consumer. Anonymous inner classes are named in the order in which they appear in the file, so Actor$1 will appear in the file before Actor$2. I don't think this is actually specified anywhere, so this is probably just a convention, and shouldn't be relied upon if you're doing anything sophisticated with multiple jvms etc.

It is possible, as jmg pointed out, that you can define multiple top level classes in the same file. If you have a public class Foo, this must be defined in Foo.java, but a non-public class can be included in another file. The above method will cope with this.

Explanation:

If you disassemble the java (javap -c -verbose), you'll see that there are line numbers in the debug information, but they only apply to methods. Using the following inner class:

static class Consumer implements Runnable {
    public void run() {
        // stuff
    }
}

and the javap output contains:

uk.co.farwell.stackoverflow.Actors$Consumer();
  Code:
   Stack=1, Locals=1, Args_size=1
   0:   aload_0
   1:   invokespecial   #10; //Method java/lang/Object."<init>":()V
   4:   return
  LineNumberTable: 
   line 20: 0

  LocalVariableTable: 
   Start  Length  Slot  Name   Signature
   0      5      0    this       Luk/co/farwell/stackoverflow/Actors$Consumer;

The LineNumberTable contains the list of line numbers which apply to a method. So my constructor for the Consumer starts at line 20. But this is the first line of the constructor, not the first line of the class. It is only the same line because I'm using the default constructor. If I add a constructor, then the line numbers will change. the compiler does not store the line that the class is declared on. So you can't find where the class is declared without parsing the java itself. You simply don't have the information available.

However, if you're using an anonymous inner class such as:

Runnable run = new Runnable() {
    public void run() {
    }
};

Then the line number of the constructor and class will match[*], so this gives you an line number.

[*] Except if the "new" and "Runnable()" are on different lines.

like image 96
Matthew Farwell Avatar answered Oct 15 '22 18:10

Matthew Farwell


You can find uut current line of code:

Throwable t = new Throwable();
System.out.println(t.getStackTrace()[0].getLineNumber());

But it looks like StackTraceElements are created by native JDK method inside Throwable.

public synchronized native Throwable fillInStackTrace();

Event if you use byte-code manipulation framework, to add a method to a class that creates throwable, you won't get proper line of code of class declaration.

like image 39
Piotr Gwiazda Avatar answered Oct 15 '22 19:10

Piotr Gwiazda