Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java class add a method to itself at runtime?

Can a class add a method to itself at runtime (like from a static block), so that if someone is performing reflection on this class, they'll see the new method, even though it wasn't defined at compile time?

Background:

A framework I'm using expects Action classes to be defined that have a doAction(...) method, by convention. The framework inspects these classes at runtime to see what type of parameters are available in their doAction() method. For example: doAction(String a, Integer b)

I'd like each class to be able to programatically generate its doAction() method with various parameters, just-in-time when it is inspected. The body of the method can be empty.

like image 233
slattery Avatar asked Jul 13 '11 14:07

slattery


People also ask

Can a class method be called from the class itself?

To call a class method, put the class as the first argument. Class methods can be can be called from instances and from the class itself. All of these use the same method. The method can use the classes variables and methods.

Can we create a class at runtime in Java?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.

What is the purpose of the runtime class?

Runtime class is a subclass of Object class, can provide access to various information about the environment in which a program is running. The Java run-time environment creates a single instance of this class that is associated with a program.

Which means attaching a message to a method at run time?

Connecting a method call to the method body is known as binding. Static Binding (also known as Early Binding).


1 Answers

It's not simple. Once a class is loaded by a classloader, there is no way to change the methods of loaded classes. When a class is requested, a classloader will load it and link it. And there is no way (with Java) to change the linked code or to add/remove methods.

The only trick that comes to my mind is playing with classloaders. If we delete a custom classloader, then the classes loaded by that classloader should be deleted or inaccessible too. The idea that comes to my mind is to

  1. implement one custom classloader
  2. load the dynamic class with that custom classloader
  3. if we have an updated version of this class,
  4. remove the custom classloader and
  5. load the new version of this class with a new instance of the custom classloader

I leave that as food for thought, can't prove, if this leads to a solution or if we have pitfalls.

As a simple answer to the question: No, we can't change a loaded class like we can change the content of fields with reflection. (we can't add or remove fields too).

like image 118
Andreas Dolk Avatar answered Oct 01 '22 03:10

Andreas Dolk