Generating classes at runtime and invoking their methods with and without the use of Reflection in Java
Tags: java, tutorial, classes, generation
Published: 2020-12-08 16:43:29

The generation of classes at runtime is an advanced topic that requires a lot of knowledge that can be reduced if you use particular libraries that perform the most complex functions to accomplish this task.
So, for this purpose, we can use the **ClassFactory** component and the sources generating components of the [**Burningwave Core**](https://burningwave.github.io/core/) library by adding to our pom.xml the following dependency:
{% gist https://gist.github.com/Roberto-Gentili/536ee2d3f775030d46d82a008da10dbe.js %}
After this we set the code to be generated in **UnitSourceGenerator** objects and we must pass it to **loadOrBuildAndDefine** method of ClassFactory with the ClassLoader where you want to define newly generated classes.

This method performs the following operations: tries to load all the classes present in the UnitSourceGenerator through the class loader, if at least one of these is not found it proceeds to compile all the UnitSourceGenerators and uploading their classes on class loader: **in this case, keep in mind that if a class with the same name was previously loaded by the class loader, the compiled class will not be uploaded**. **If you need more information you can**:
* see a [**complete example about source code generators**](https://github.com/burningwave/core/blob/master/src/test/java/org/burningwave/core/UnitSourceGeneratorTest.java#L153)
* read [**this guide**](https://github.com/burningwave/core/wiki/FAQ#how-can-i-use-classes-located-outside-the-runtime-class-path-in-my-sources-to-be-generated) where you also can find a link to an [**example about generating classes by using libraries located outside the runtime class paths**](https://github.com/burningwave/core/blob/master/src/test/java/org/burningwave/core/examples/classfactory/ExternalClassRuntimeExtender.java)
* go [**here**](https://github.com/burningwave/core/tree/master/src/test/java/org/burningwave/core/examples/classfactory) for more examples
* [**ask for assistance on GitHub**](https://github.com/burningwave/core/discussions)
* [**ask Stack Overflow for assistance**](https://stackoverflow.com/search?q=burningwave)

Once the classes have been compiled and loaded, it is possible to invoke their methods in severals ways as shown at the end of the example below.

```java
UnitSourceGenerator unitSG = UnitSourceGenerator.create("packagename").addClass(
    ClassSourceGenerator.create(
        TypeDeclarationSourceGenerator.create("MyExtendedClass")
    ).addModifier(
        Modifier.PUBLIC
    //generating new method that override MyInterface.convert(LocalDateTime)
    ).addMethod(
        FunctionSourceGenerator.create("convert")
        .setReturnType(
            TypeDeclarationSourceGenerator.create(Comparable.class)
            .addGeneric(GenericSourceGenerator.create(Date.class))
        ).addParameter(VariableSourceGenerator.create(LocalDateTime.class, "localDateTime"))
        .addModifier(Modifier.PUBLIC)
        .addAnnotation(AnnotationSourceGenerator.create(Override.class))
        .addBodyCodeLine("return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());")
        .useType(ZoneId.class)
    ).addConcretizedType(
        MyInterface.class
    ).expands(ToBeExtended.class)
);
System.out.println("\nGenerated code:\n" + unitSG.make());
//With this we store the generated source to a path
unitSG.storeToClassPath(System.getProperty("user.home") + "/Desktop/bw-tests");
ComponentSupplier componentSupplier = ComponentContainer.getInstance();
ClassFactory classFactory = componentSupplier.getClassFactory();
//this method compile all compilation units and upload the generated classes to default
//class loader declared with property "class-factory.default-class-loader" in 
//burningwave.properties file (see "Overview and configuration").
//If you need to upload the class to another class loader use
//loadOrBuildAndDefine(LoadOrBuildAndDefineConfig) method
ClassFactory.ClassRetriever classRetriever = classFactory.loadOrBuildAndDefine(
    unitSG
);
Class<?> generatedClass = classRetriever.get(
    "packagename.MyExtendedClass"
);
ToBeExtended generatedClassObject =
    Constructors.newInstanceOf(generatedClass);
generatedClassObject.printSomeThing();
System.out.println(
    ((MyInterface)generatedClassObject).convert(LocalDateTime.now()).toString()
);
//You can also invoke methods by casting to Virtual (an interface offered by the
//library for faciliate use of runtime generated classes)
Virtual virtualObject = (Virtual)generatedClassObject;
//Invoke by using reflection
virtualObject.invoke("printSomeThing");
//Invoke by using MethodHandle
virtualObject.invokeDirect("printSomeThing");
System.out.println(
    ((Date)virtualObject.invokeDirect("convert", LocalDateTime.now())).toString()
);
classRetriever.close();
```

In this short article we have learned how to generate classes at runtime in Java, how to load them and create instances; the complete source is available at this at [**this page**](https://www.burningwave.org/generating-classes-at-runtime-and-invoking-their-methods-with-and-without-the-use-of-reflection/).