Reputation: 999
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?
Upvotes: 1
Views: 389
Reputation: 298143
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.
Upvotes: 2
Reputation: 39451
The bytecode for a method refers to entries in the class's constant pool, so it doesn't make sense in isolation.
Upvotes: 1