How to get the line number of a method?

后端 未结 3 896
情歌与酒
情歌与酒 2020-11-28 13:29

Is it possible to get the line number of an method using reflection or other magic?
It is possible if the method is inside the current Stacktrace. Using Thread.c

3条回答
  •  执笔经年
    2020-11-28 13:56

    For me the answer of Quaternion pointing to Javassist is the perfect solution to this question. It works for me and you can use it also when you only get the java.lang.reflect.Method object.

    This is how I did it:

    Method m; // the method object
    ClassPool pool = ClassPool.getDefault();
    CtClass cc = pool.get(m.getDeclaringClass().getCanonicalName());
    CtMethod javassistMethod = cc.getDeclaredMethod(m.getName());
    int linenumber = javassistMethod.getMethodInfo().getLineNumber(0);
    

提交回复
热议问题