Write and implement new Java class files at run time

Is it possible to "import" a new Java class into a running program and use it in some way?

I can let the program create a type of ' Java 'and then include it in the project file and reference it without restarting the program?

Here is an example of what I mean:

import java.io.*;

public class Program {

File JClass = new File("JClass.java");
public static BufferedWriter out = null;

    public static void main(String[] args) {
        try {
            out = new BufferedWriter(new FileWriter("JClass.java"));
            out.write("public abstract class JClass {");
            out.newLine();
            out.newLine();
            out.write("    public void printSomething(String a) {");
            out.newLine();
            out.write("        System.out.println(a);");
            out.newLine();
            out.write("    }");
            out.newLine();
            out.write("}");
            out.close();
        } catch (IOException e)
        {
            System.exit(-1);
        }

        //Somehow import JClass.java as a class here

        JClass.printSomething("Yay! It worked!");
    }

}

Generated 'jclass Java 'file:

public abstract class JClass {

    public void printSomething(String a) {
        System.out.println(a);
    }
}

Similarly, can you create a copy of one of the project source files, edit the code in the file, and then force changes to the running program in some way?

At this point, I don't care about practical application I'm just exploring different ideas related to programming I also understand that this can be all kinds of disasters Editing running code and including dynamic classes (I can't imagine checking for errors because other classes are building projects) can produce very unpredictable results I just want to play with the idea

In other words, if anyone has any useful warnings or precautions, I would be grateful Otherwise, if people don't respond "this is a bad idea" or "there are simpler and better ways to solve the problem", I will be grateful I'm not trying to solve this problem I'm just exploring the idea

So, is that possible?

Solution

Javassist will allow you to modify existing classes and create new classes at run time

In javassist tutorial, there is a section for defining new classes from scratch Check the API to see how to add new methods, etc Check ctnewmethod. In javassist API make.

Javassist is something JBoss uses to implement aspect - oriented programming

You can also look at eats (instrumentation methods will be of interest to you), which uses javassist to add new code to existing methods at run time Eats is not a released version, but it is valid: o

JPDA provides some mechanisms to modify classes that have been loaded and run in the JVM

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>