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 don't know the classes at compile time.
What I mean exactly by overriding at runtime:
abstract class MyClass{ public void myMethod(); } class Overrider extends MyClass{ @Override public void myMethod(){} } class Injector{ public static void myMethod(){ // STATIC !!! // do actual stuff } } // some magic code goes here Overrider altered = doMagic( MyClass.class, Overrider.class, Injector.class);
Now, this invocation...
altered.myMethod();
...would call Injector.myMethod() instead of Overrider.myMethod().
Injector.myMethod() is static, because, after doing "magic" it is invoked from different class instance (it's the Overrider), (so we prevent it from accessing local fields).
As others said, no, you can't override a method at runtime.
The getConstructors() method is used to get the public constructors of the class to which an object belongs. The getMethods() method is used to get the public methods of the class to which an object belongs. We can invoke a method through reflection if we know its name and parameter types.
Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Overriding methods in the same classBoth methods must have the same name, same parameters and, same return type else they both will be treated as different methods. The method in the child class must not have higher access restrictions than the one in the superclass.
You can use something like cglib for generating code on-the-fly
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With