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
18,714 views

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");
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) {

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return source;
        }

       @Override
       public OutputStream openOutputStream() throws IOException{
           return byteArrayOutputStream;
       }
};

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

        @Override
        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");

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

and instantiated :

final Object o = aClass.newInstance();
System.out.println(o);

When run, the console will output "HelloWorld 

answered Apr 15, 2020 by Gitika
• 65,890 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,190 points
819 views
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,120 points
2,369 views
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,520 points
656 views
0 votes
0 answers

How to add a class to a given element?

I already have a class for an element: <div class="someclass"> <img ... ...READ MORE

Sep 28, 2022 in Java by Nicholas
• 7,760 points
373 views
+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 7, 2018 by Omkar 81,112 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,230 points
2,280 views
+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
1,222 views
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,620 points
1,169 views
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,140 points
1,482 views
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 28, 2018 in Java by samarth295
• 2,220 points
2,459 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP