如何反射性地打印方法主体? [英] How do I print the method body reflectively?

查看:29
本文介绍了如何反射性地打印方法主体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有

private static void getMethods(Class<? extends Object> clazz) {
    Method[] declaredMethods = clazz.getDeclaredMethods();
    for (Method aMethod : declaredMethods) {
      aMethod.setAccessible(true);

      // Print the declaration
      System.out.print(Modifier.toString(aMethod.getModifiers()) + " "
          + aMethod.getReturnType().getSimpleName() + " " + aMethod.getName());

      // Get Parameter Types
      getParameters(aMethod);

      //Empty Body
      System.out.println("{}
");
    }
  }

反射打印大部分信息,但创建一个空的主体.如何添加 Java 的反射特性以打印方法体?

Which prints most information reflectively but creates an empty body. How do I add to the reflective nature of Java to print the method body?

推荐答案

如何添加 Java 的反射特性来打印方法体?

How do I add to the reflective nature of Java to print the method body?

恐怕难度很大.

首先,原始源代码很可能对正在运行的程序不可用.通常,开发人员不会在二进制 JAR 中包含源代码.(即使他们这样做,也不能保证他们将是真正的"来源.)

For a start, the original source code is most likely to be unavailable to a running program. As a rule, developers do not include source code in the binary JARs. (And even if they do, there is not guarantee that they will be the "real" sources.)

您通常可以通过将类的 FQN 转换为字节码文件并使用类类加载器将文件作为资源流加载来获取类的字节码.但是不能保证您以这种方式获得的字节码与加载的字节码相同.(一些类加载器出于各种原因处理字节码.)

You can usually obtain the bytecodes for the class by translating the FQN for the class into the bytecode file and using the classes classloader to load the file as a resource stream. But it is not guaranteed that the bytecodes you get this way will be the same as what were loaded. (Some classloaders mess around with the bytecodes for various reasons.)

假设您可以获得真正的字节码,最后一步将是原始显示它们,或者将它们反汇编或反编译为更具可读性的内容.您应该能够使用 javap 进行反汇编,但反编译需要使用第三方产品.当然,反编译后的代码看起来与原始代码有很大不同,如果字节码被混淆了,它们的源代码将非常不可读.

Assuming that you can get the real bytecodes, the last step will be to either display them raw, or disassemble or decompile them to something more readable. You should be able to use javap to do a disassembly, but decompilation would entail using a third party product. Of course, the decompiled code will look significantly different to the original code, and if the bytecodes have been obfuscated they source code will be pretty much unreadable.

这篇关于如何反射性地打印方法主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆