臨時文件動態編譯java代碼 – JAVA編程語言程序開發技術文章

本程序出自群裡.22069957 之前用到這個功能在網頁上動態生成用戶寫的代碼..共享給大傢.


 



import java.io.File;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;


public class demo {
    public demo(String s) {
        try {


            System.getProperties().store(System.out, “”);


            JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            DiagnosticCollector diagnostics = new DiagnosticCollector();
            StandardJavaFileManager fileManager = compiler
                    .getStandardFileManager(diagnostics, null, null);
            String fileName = “MyButton.java”;


            File file = new File(System.getProperty(“java.io.tmpdir”), fileName);
            PrintWriter pw = new PrintWriter(file);
            pw.println(s);
            pw.close();


            Iterable compilationUnits = fileManager
                    .getJavaFileObjectsFromStrings(Arrays.asList(file
                            .getAbsolutePath()));
            JavaCompiler.CompilationTask task = compiler.getTask(null,
                    fileManager, diagnostics, null, null, compilationUnits);
            boolean success = task.call();
            fileManager.close();
            System.out.println((success) ? “編譯成功” : “編譯失敗”);
            URLClassLoader classLoader = new URLClassLoader(
                    new URL[] { new File(System.getProperty(“java.io.tmpdir”))
                            .toURI().toURL() });
            final JButton btn = (JButton) classLoader.loadClass(“MyButton”)
                    .newInstance();
            btn.setText(“按鈕”);
            System.out.println(btn);
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    JFrame frame = new JFrame(“frame”);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setSize(640, 480);
                    frame.setLocationRelativeTo(null);
                    frame.getContentPane().add(btn);
                    frame.setVisible(true);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String args[]) {
        new demo(
                “import javax.swing.JButton; public class MyButton extends JButton {}”);
    }
}

發佈留言