Can I modify the byte code of a Java method in the runtime?

后端 未结 4 944
花落未央
花落未央 2021-01-03 01:18

I am writing a plugin of another large java program .

I want to modify some byte code of some java method of the java program during runtime, so that I can intercept

相关标签:
4条回答
  • 2021-01-03 01:38

    Sorry, but this is not possible. First off, bytecode is immutable after classloading. The JVM provides several APIs that can be used to do something like this, but they are obviously highly privileged.

    If you're running in a low privilege environment like a browser Applet, then you're obviously not going to be allowed to do this, and any method you could should be considered a security vulnerability.

    But the question is why you are using applets in the first place, and why you want to modify code after loading. There's almost certainly a better way to do what you're trying to do.

    0 讨论(0)
  • 2021-01-03 01:42

    There are several libraries which you can use. See for example here. Once a class was already loaded/initialized by the VM it will be impossible to manipulate, though.

    By the way, in principle you can also just replace the class to be 'hooked' with your own proxy class file. As long as the class' visible interface does not change this may work. (Sub-classes of the class may horribly fail at runtime though.) This replacement can be as easy as changing the classpath so that your class of the same name will be found first, before the original one. Delegating to the original class of the same name may be a little more complex in this case.

    0 讨论(0)
  • 2021-01-03 01:42

    Yes, you can, but the process would be a bit tricky, as you would operate directly with memory. For this purpose, you'd look at unofficial documentation on sun.misc package and its Unsafe class.

    • Warning 1: the Unsafe class would be removed in JDK 9 according to official sources.
    • Warning 2: the Sun company would not take responsibility for your code to work correctly, as this class should not be used at all, and exists for system usage only.
    0 讨论(0)
  • 2021-01-03 01:46

    Just use -javaagent opiton, which is used to modify the bytecode at runtime. You can find more about -javaagent from This Link or from This Link

    0 讨论(0)
提交回复
热议问题