Java – how to get the line number of a method?

Can I get the line number of using reflection or other magic methods?

Solution

I want to do the same thing. After some research, I solved javassist You will need to add javassist (I use version 3.15.0 - GA)

The following class is given to determine the location of the "X" method The method name "X" is hard coded, but if you are on the same ship as me, reflection is not difficult, so I believe you can get a list of method names, and then the following method will let you get the line number:

public class Widget {
    void x(){System.out.println("I'm x\n");}
    //comment added to create space
    void y(){System.out.println("I'm y\n");} 
}
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;

public class App {
    public static void main(String[] args) throws NotFoundException {
        System.out.println("Get method line number with javassist\n");
        ClassPool pool = ClassPool.getDefault();
        CtClass cc = pool.get("com.quaternion.demo.Widget");
        CtMethod methodX = cc.getDeclaredMethod("x");
        int xlineNumber = methodX.getmethodInfo().getLineNumber(0);
        System.out.println("method x is on line " + xlineNumber + "\n");
    }
}

Output: method X is accurate in my case on line 12. I deleted some comments

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>