栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

如果仅用于测试,则可能有效。它假定可以通过调用类的类访问类文件

ClassLoader
,并且类文件已使用调试符号进行编译(我希望它们用于测试!)。此代码依赖于ASM字节码库。

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<String> methodDescriptorReference = new AtomicReference<String>();    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");}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/496716.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号