java获取行号,如何获取方法的行号?

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.currentThread().getStackTrace(), one can get the line number of an StackTraceElement. But what can I do if I only got the java.lang.reflect.Method Object?

解决方案

I wanted to do the same thing and after some research settled on javassist. You will need to add javassist (I used version 3.15.0-GA).

Given the following class determine the location of the "x" method. The method name "x" is hard coded however if you are in the same boat as me, the reflection isn't hard so I'm confident you can get a list of method names, then the following will let you get the line numbers of the methods:

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 on line 12 which in my case is accurate I cut out some comments...

Note: As mentioned by Pete83 in the comments, this method actually returns the first line of code in the method and not the line which declares the method. This usually won't be an issue as most will probably want to establish relative position (the order in which they were declared) and use this information for your own conventions. This would come up any time you felt the need to include an ordinal value within an annotation which could be readily determined by the position within the code itself.

For quick reference Maven coordinates for javassist:

org.javassist

javassist

3.15.0-GA

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值