Creating a dynamic function in Java

So, I'm trying to figure out if there is any method to dynamically create / assign a method to a class in Java. If it were C, I would just do it this way with pointers:

public class Foo { void bar(void *ptr) {....} }; int main() { Foo f = new Foo(); f.bar({"my function" ...}) } 

However, Java, of course, has no pointers, so is there a way to get similar functionality from a Java application?

+4
source share
7 answers

In Java, you usually declare an interface with a called method. For example, if your function just wants to execute some code, you should declare Runnable and implement your execution method.

 public class Foo { void bar(Runnable function) { for(int i = 0; i < 5; i++) { function.run(); } } static void myFunction() { System.out.println("my Function!"); } public static void main(String[] ignored) { Foo f = new Foo(); f.bar( new Runnable() { public void run() { myFunction(); }}); } } 
+4
source

To generate truly dynamic methods, you will need a bytecode manipulation library such as Javassist or cglib .

+2
source

In java this is achieved by what are called anonymous classes, here is an example -

 abstract class Bar { public void myfunc(); } public class Client { public void execute() { doSomething(new Bar() { // define your dynamic function here ie provide its implementation public void myfunc() { //do whatever } }); } public void doSomething(Bar b) { b.myfunc(); } } 
+1
source

You can use the Java Scripting API, create a function as a Script, and call it. But do this only if your functions are really fully defined at runtime, because interpreting scripts is always slower than implementing in native Java.

0
source

If you really want to change the classes at runtime, the only way is to actually change the bytecode, assuming your setup allows it (Java security usually works). However, in Java 6 there is a java.lang.instrument that can help:

http://download.oracle.com/javase/6/docs/api/java/lang/instrument/package-summary.html

You can also use the cglib project:

http://sourceforge.net/projects/cglib/

0
source

See http://functionaljava.org/ for the entire functional library for Java.

0
source

Here's a link to how you can use the built-in version of javac to compile classes that you define on the fly.

0
source

Source: https://habr.com/ru/post/1343811/


All Articles