Generating and compiling runtime code

Let's say I have this code that uses some input (like a URL path) to determine which method to run, via reflection:

// init
map.put("/users/*", "viewUser");
map.put("/users", "userIndex");

// later
String methodName = map.get(path);
Method m = Handler.class.getMethod(methodName, ...);
m.invoke(handler, ...);

This uses reflection, so performance can be improved. This can be done as follows:

// init
map.put("/users/*", new Runnable() { public void run() { handler.viewUser(); } });
map.put("/users", new Runnable() { public void run() { handler.userIndex(); } });

// later
Runnable action = map.get(path);
action.run();

But for manually creating all of these Runnable, as this has its problems. I am wondering if I can create them at runtime? Therefore, I will have an input map, as in the first example, and will dynamically create a map of the second example. Of course, generation is just a matter of constructing a string, but what about compiling and loading it?

. , , . , .

+3
4

- , , . - . , , . , - , .

+3

, . , , , , , .

, API- 1.6, "" : Compiler Iterable<JavaFileObject>, JavaFileManager, , .

, , ClassLoader, FQCN ..

, , , ;)

+2

, , . ( Method, .)

+1

Well, you can write the code in a .java file, compile it using javac ( how to do it ), and load it into Java using Reflection.

But perhaps, as a compromise, you can also get Method objects during initialization - so you just need to call the invoke () method for each request.

0
source

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


All Articles