How to generate a class at runtime

0 votes
Is there a library that facilitates classes code generation at runtime?
Apr 15, 2020 in Java by Edvard
• 180 points

2 answers to this question.

+1 vote
Best answer
Yes, I recently met this library which among other things helps to create classes at runtime: here is the detailed example
answered Apr 15, 2020 by Edureka
• 520 points

selected Apr 15, 2020 by Edvard
+1 vote

Hey, @Edvard,

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance. Although compiling the source into a class is slow, the newly created class will be treated by the JVM just like any other class.

This is an example to create and used a dynamically created class without creating any intermediate files.

First the source is created using string builder

final String className = "HelloWorld";
final String path = "com.bounded.buffer";
final String fullClassName = path.replace('.', '/') + "/" + className;
final StringBuilder source = new StringBuilder();
source.append("package " + path+";");
source.append("public class " + className + " {\n");
source.append(" public String toString() {\n");
source.append("     return \"HelloWorld - Java Dynamic Class Creation...";");
source.append(" }\n");

This is where the magic happens - the StringBuilder java source, is turned into byte code :

final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

final SimpleJavaFileObject simpleJavaFileObject
      = new SimpleJavaFileObject(URI.create(fullClassName + ".java"), SOURCE) {

        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return source;

       public OutputStream openOutputStream() throws IOException{
           return byteArrayOutputStream;

final JavaFileManager javaFileManager = new ForwardingJavaFileManager(
    getStandardFileManager(null, null, null)) {

        public JavaFileObject getJavaFileForOutput(
            Location location,String className,
            JavaFileObject.Kind kind,
            FileObject sibling) throws .. {
           return simpleJavaFileObject;

ToolProvider.getSystemJavaCompiler().getTask(null, javaFileManager, null, null, null, singletonList(simpleJavaFileObject)).call();

then the bytes that make up the class are loaded into the class loader :

final byte[] bytes = byteArrayOutputStream.toByteArray(); 

// use the unsafe class to load in the class bytes
final Field f = Unsafe.class.getDeclaredField("theUnsafe");

final Unsafe unsafe = (Unsafe) f.get(null);
final Class aClass = unsafe.defineClass(fullClassName, bytes, 0, bytes.length);

and instantiated :

final Object o = aClass.newInstance();

When run, the console will output "HelloWorld 

answered Apr 15, 2020 by Gitika
• 65,870 points

Related Questions In Java

0 votes
1 answer

How to get the Generic type of class at run time?

public class GenericClass<T> { ...READ MORE

answered Jul 2, 2018 in Java by Akrati
• 3,170 points
0 votes
1 answer

How to add items in list at a time?

Hi Priyanka , I think this code snippet ...READ MORE

answered Aug 9, 2019 in Java by sampriti
• 1,100 points
0 votes
0 answers

How to manage two JRadioButtons in java so that only one of them can be selected at a time?

How to manage two JRadioButtons in java ...READ MORE

Apr 21, 2020 in Java by kartik
• 37,510 points
+5 votes
4 answers

How to execute a python file with few arguments in java?

You can use Java Runtime.exec() to run python script, ...READ MORE

answered Mar 27, 2018 in Java by DragonLord999
• 8,450 points

edited Nov 6, 2018 by Omkar 41,839 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered Aug 20, 2019 in Java by Sirajul
• 59,050 points
+1 vote
2 answers

How to generate random integers within specific range in Java?

You can achieve that concisely in Java: Random ...READ MORE

answered Jul 25, 2018 in Java by samarth295
• 2,220 points
0 votes
1 answer

How to divide a string in two parts

String s="yourstring"; boolean flag = true; for(int i=0;i<s.length();i++) { ...READ MORE

answered Apr 13, 2018 in Java by Rishabh
• 3,640 points
0 votes
2 answers

How to create a 2-D array in java?

int[][] multi = new int[5][]; multi[0] = new ...READ MORE

answered Jul 16, 2018 in Java by Daisy
• 8,110 points
0 votes
3 answers

How to read a Text File in Java?

You can use readAllLines and the join method to ...READ MORE

answered Jul 27, 2018 in Java by samarth295
• 2,220 points
0 votes
2 answers

How to test that an array contains a certain value?

public static final String[] VALUES = new ...READ MORE

answered Jul 17, 2018 in Java by Sushmita
• 6,890 points