临时文件动态编译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, 
nullnull);
            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, 
nullnull, 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(
640480);
                    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 {}");
    }

}

posted on 2010-02-04 23:49 相信 阅读(590) 评论(0)  编辑  收藏 所属分类: Swing文章


只有注册用户登录后才能发表评论。


网站导航:
 
<2024年3月>
252627282912
3456789
10111213141516
17181920212223
24252627282930
31123456

导航

统计

公告

不显示applet

常用链接

留言簿(16)

我参与的团队

随笔档案

文章分类

文章档案

新闻档案

相册

swingchina 专业搞Swing的网站

搜索

最新评论

阅读排行榜

评论排行榜