I understand if I have a class file I can load it at run time and execute it's methods through classLoader. However, what if I only have bytecode or java code for a single method? Is it possible to dynamically create a class at run time and then invoke the method?
-
1Possible duplicate of Interpret something, and run the generated bytecode in Java?SirFartALot– SirFartALot2019-05-20 06:00:00 +00:00Commented May 20, 2019 at 6:00
-
But in that case wouldn't I need to have the bytecode for entire class? I only have one method's bytecode.Tehreem– Tehreem2019-05-20 06:41:29 +00:00Commented May 20, 2019 at 6:41
-
You can declare the method only inside the Class. Using any byte code library you can create a class at run time and define your method (via code) in that class.Ramesh Subramanian– Ramesh Subramanian2019-05-20 06:43:54 +00:00Commented May 20, 2019 at 6:43
2 Answers
There is a planned feature, JEP 8158765: Isolated Methods, also on the bugtracking list, which would allow to load and execute such bytecode, without generating a fully materialized Class. It could look like
MethodHandle loadCode(String name, MethodType type, byte[] instructions, Object[] constants)
in the class MethodHandles.Lookup
However, this feature is in draft state, so it could take significant time before becoming an actual API and it might even happen that it gets dropped in favor of an entirely different feature covering the use cases the authors of the JEP have in mind.
Until then, there is no way around generating the necessary bytes before and after the method’s bytecode, to describe a complete class and loading that class. But of course, you can write your own method accepting a method’s byte code and some metadata, like the expected signature, generating such a class and reuse that method.
Note that there’s an alternative to creating a new ClassLoader, Class<?> defineClass(byte[] bytes) in class MethodHandles.Lookup which allows to add a class to an existing class loading context, since Java 9.
2 Comments
MethodHandle API itself, which has to create a lot of classes internally when optimizing the adapters, like creating an entire class, just to denote that one handle is dropping one of its arguments before calling into another. That’s the first overhead to eliminate with that feature.The bytecode for a method refers to entries in the class's constant pool, so it doesn't make sense in isolation.
2 Comments
public static int add(int left, int right) { return left + right; } this will blindly load first two arguments from the stack and add them.