Creating a dynamic Java class

I generate a dynamic class in my java program, writing all my code to a java file, compiling the java file into a class file and then loading the class file using URLClassLoader. The problem is that it creates a lot of files on my computer. This is their way of doing this, only by creating "virtual files" (file objects) and not generating any real files, because the way they do it takes time and seems unclean and inefficient.

+5
source share
3 answers

If you look at the ClassLoader class, it has a way to determine the class from the actual series of bytes.

Java docs for ClassLoader

, , , , ClassLoader , . , .

, , URLClassLoader ClassLoader .

+1

A () :

  • ClassLoader, ClassLoader
  • ClassLoader .class.

-, - . ( , SimpleFileVisitor . Java.NIO.)

public class CustomClassLoader extends ClassLoader {

    @Override
    public Class findClass(String binaryClassName) {
        byte[] b = customLoadClassData(binaryClassName);
        return defineClass(binaryClassName, b, 0, b.length);
    }

    private byte[] customLoadClassData(String binaryClassName) {
        // Be sure to read in the specific .class file you want.
        // A tip is to handle this *outside* of this class.
    }

}

:

CustomClassLoader loader = new CustomClassLoader();
Class clazz = loader.findClass("com.stackoverflow.some.binary.name");

... , null.

0

The bytecode generation and processing libraries allow you to modify and generate classes on the fly in memory. Javassist is probably the easiest to get started as it allows you to use Java syntax.

They also have lighter weight than all standalone compilers.

0
source

All Articles