Java reflection: How do I override or generate methods at runtime?

后端 未结 5 1102
难免孤独
难免孤独 2020-12-05 03:08

It is possible in plain Java to override a method of a class programmatically at runtime (or even create a new method)?

I want to be able to do this even if I

相关标签:
5条回答
  • 2020-12-05 03:32

    I wrote an article for java.net about how to transparently add logging statements to a class when it is loaded by the classloader using a java agent.

    It uses the Javassist library to manipulate the byte code, including using the Javassist compiler to generate extra bytecode which is then inserted in the appropriate place, and then the resulting class is provided to the classloader.

    A refined version is available with the slf4j project.

    0 讨论(0)
  • 2020-12-05 03:34

    For interfaces there is java.lang.reflect.Proxy.

    For classes you'll either need a third-party library or write a fair bit of code. Generally dynamically creating classes in this way is to create mocks for testing.

    There is also the instrumentation API that allows modification of classes. You can also modify classes with a custom class loader or just the class files on disk.

    0 讨论(0)
  • 2020-12-05 03:41

    You can use something like cglib for generating code on-the-fly

    0 讨论(0)
  • 2020-12-05 03:41

    In java6 has been added the possibility to transform any already loaded class. Take a look at the changes in the java.lang.instrument package

    0 讨论(0)
  • 2020-12-05 03:47

    If I got it right, the main problem that concerns you is how to pass a static method delegate (like in C#), through the instance interface method.

    You can check this article: A Java Programmer Looks at C# Delegates (archived), which shows you how to get a reference to your static method and invoke it. You can then create a wrapper class which accepts the static method name in its constructor, and implements your base class to invoke the static method from the instance method.

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