当前位置:编程学习 > 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 {}");
    }
}

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,