Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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).

like image 893
ivan_ivanovich_ivanoff Avatar asked Jun 28 '09 11:06

ivan_ivanovich_ivanoff


People also ask

Can an object's method be overridden with a custom implementation at runtime?

As others said, no, you can't override a method at runtime.

Which method is used to get methods using reflection?

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.

What are reflections in Java is it compile time or runtime?

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.

How do you override a method in the same class?

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.


1 Answers

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

like image 83
oxbow_lakes Avatar answered Oct 14 '22 15:10

oxbow_lakes