java 获取调用的方法,获取调用方法(java.lang.reflect.Method)

I would like to get the calling method java.lang.reflect.Method. NOT the name of the method.

Here is an example how to get the callers Class.

// find the callers class

Thread t = Thread.getCurrentThread();

Class> klass = Class.forName(t.getStackTrace()[2].getClassName());

// do something with the class (like processing its annotations)

...

It's for testing purpose only!

解决方案

If it's just for testing, then this may work. It assumes that the class files are accessible via the calling class's ClassLoader and that the class files were compiled with debugging symbols (which I hope they are for testing!). This code relies on the ASM bytecode library.

public static Method getMethod(final StackTraceElement stackTraceElement) throws Exception {

final String stackTraceClassName = stackTraceElement.getClassName();

final String stackTraceMethodName = stackTraceElement.getMethodName();

final int stackTraceLineNumber = stackTraceElement.getLineNumber();

Class> stackTraceClass = Class.forName(stackTraceClassName);

// I am only using AtomicReference as a container to dump a String into, feel free to ignore it for now

final AtomicReference methodDescriptorReference = new AtomicReference();

String classFileResourceName = "/" + stackTraceClassName.replaceAll("\\.", "/") + ".class";

InputStream classFileStream = stackTraceClass.getResourceAsStream(classFileResourceName);

if (classFileStream == null) {

throw new RuntimeException("Could not acquire the class file containing for the calling class");

}

try {

ClassReader classReader = new ClassReader(classFileStream);

classReader.accept(

new EmptyVisitor() {

@Override

public MethodVisitor visitMethod(int access, final String name, final String desc, String signature, String[] exceptions) {

if (!name.equals(stackTraceMethodName)) {

return null;

}

return new EmptyVisitor() {

@Override

public void visitLineNumber(int line, Label start) {

if (line == stackTraceLineNumber) {

methodDescriptorReference.set(desc);

}

}

};

}

},

0

);

} finally {

classFileStream.close();

}

String methodDescriptor = methodDescriptorReference.get();

if (methodDescriptor == null) {

throw new RuntimeException("Could not find line " + stackTraceLineNumber);

}

for (Method method : stackTraceClass.getMethods()) {

if (stackTraceMethodName.equals(method.getName()) && methodDescriptor.equals(Type.getMethodDescriptor(method))) {

return method;

}

}

throw new RuntimeException("Could not find the calling method");

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值