Sometimes it's necessary or more comfortably to generate classes. To use this classes, the classes must be loaded into to the JVM, for that you need a classloader. Usually the method ClassLoader#defineClass() is used for that purpose. But this Method has the scope protected, so you can't access it outside of the class hierarchy. For this reason the ByteCodeClassLoader exists. To load a class you need the bytecode and the name of the class in the binary format (JSL §13.1, ), which means the full qualified class name, separated with dots ('.').
To get a instance of the Classloader you call
1 | ByteCodeClassLoader classLoader = ByteCodeClassLoader.getClassLoader(); |
Then your bytecode could be loaded with
1 2 | Class<?> classInstance = classLoader.load(className, byteCode); classInstance.newInstance(); |
or with
1 2 | ByteCodeContainer generatedClass = AwesomeByteCodeGenerator.generate(); classLoader.load(generatedClass); |
ByteCodeContainer is a container objects which hold the class name and the bytecode.