Advertisement
Guest User

Pascal Thivent

a guest
Apr 11th, 2010
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.25 KB | None | 0 0
  1. /*
  2.  * Copyright 2005-2006 Sun Microsystems, Inc.  All Rights Reserved.
  3.  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4.  *
  5.  * This code is free software; you can redistribute it and/or modify it
  6.  * under the terms of the GNU General Public License version 2 only, as
  7.  * published by the Free Software Foundation.
  8.  *
  9.  * This code is distributed in the hope that it will be useful, but WITHOUT
  10.  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11.  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12.  * version 2 for more details (a copy is included in the LICENSE file that
  13.  * accompanied this code).
  14.  *
  15.  * You should have received a copy of the GNU General Public License version
  16.  * 2 along with this work; if not, write to the Free Software Foundation,
  17.  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18.  *
  19.  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  20.  * CA 95054 USA or visit www.sun.com if you need additional information or
  21.  * have any questions.
  22.  */
  23.  
  24. /*
  25.  * @(#)CompileFromString.java   1.11 07/05/05
  26.  */
  27. package sun.tools.evalexpr;
  28.  
  29. import static javax.tools.StandardLocation.*;
  30.  
  31. import java.lang.reflect.Method;
  32. import java.util.ArrayList;
  33. import java.util.Arrays;
  34. import java.util.List;
  35.  
  36. import javax.swing.JOptionPane;
  37. import javax.tools.DiagnosticListener;
  38. import javax.tools.JavaCompiler;
  39. import javax.tools.JavaFileObject;
  40. import javax.tools.ToolProvider;
  41.  
  42. /**
  43.  * JSR 199 Demo application: compile from a String.
  44.  * <p>
  45.  * <b>This is NOT part of any API supported by Sun Microsystems. If you write code that depends on this, you do so at
  46.  * your own risk. This code and its internal interfaces are subject to change or deletion without notice.</b>
  47.  * </p>
  48.  *
  49.  * @author Peter von der Ah&eacute;
  50.  */
  51. public class CompileFromString {
  52.  
  53.     /**
  54.      * The name of the class used to evaluate expressions.
  55.      */
  56.     private final static String CLASS_NAME = "EvalExpression";
  57.  
  58.     /**
  59.      * Object used to signal errors from evalExpression.
  60.      */
  61.     public final static Object ERROR = new Object() {
  62.         @Override
  63.         public String toString() {
  64.             return "error";
  65.         }
  66.     };
  67.  
  68.     /**
  69.      * Compile and evaluate the specified expression using the given compiler.
  70.      *
  71.      * @param compiler a JSR 199 compiler tool used to compile the given expression
  72.      * @param expression a Java Programming Language expression
  73.      * @return the value of the expression; ERROR if any errors occured during compilation
  74.      * @throws java.lang.Exception exceptions are ignored for brevity
  75.      */
  76.     public static Object evalExpression(JavaCompiler compiler, DiagnosticListener<JavaFileObject> listener,
  77.         List<String> flags, String expression) throws Exception {
  78.         // Use a customized file manager
  79.         MemoryFileManager mfm = new MemoryFileManager(compiler.getStandardFileManager(listener, null, null));
  80.  
  81.         // Create a file object from a string
  82.         JavaFileObject fileObject = mfm.makeSource(CLASS_NAME, "public class " + CLASS_NAME + " {\n"
  83.             + "    public static Object eval() throws Throwable {\n" + "        return " + expression + ";\n"
  84.             + "    }\n}\n");
  85.  
  86.         JavaCompiler.CompilationTask task = compiler.getTask(null, mfm, listener, flags, null, Arrays
  87.             .asList(fileObject));
  88.         if (task.call()) {
  89.             // Obtain a class loader for the compiled classes
  90.             ClassLoader cl = mfm.getClassLoader(CLASS_OUTPUT);
  91.             // Load the compiled class
  92.             Class compiledClass = cl.loadClass(CLASS_NAME);
  93.             // Find the eval method
  94.             Method eval = compiledClass.getMethod("eval");
  95.             // Invoke it
  96.             return eval.invoke(null);
  97.         } else {
  98.             // Report that an error occured
  99.             return ERROR;
  100.         }
  101.     }
  102.  
  103.     /**
  104.      * Main entry point for program; ask user for expressions, compile, evaluate, and print them.
  105.      *
  106.      * @param args ignored
  107.      * @throws java.lang.Exception exceptions are ignored for brevity
  108.      */
  109.     public static void main(String... args) throws Exception {
  110.         // Get a compiler tool
  111.         final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  112.         final List<String> compilerFlags = new ArrayList();
  113.         compilerFlags.add("-Xlint:all"); // report all warnings
  114.         compilerFlags.add("-g:none"); // don't generate debug info
  115.         String expression = "System.getProperty(\"java.vendor\")";
  116.         while (true) {
  117.             expression = JOptionPane.showInputDialog("Please enter a Java expression", expression);
  118.             if (expression == null) {
  119.                 return; // end program on "cancel"
  120.             }
  121.             long time = System.currentTimeMillis();
  122.             Object result = evalExpression(compiler, null, compilerFlags, expression);
  123.             time = System.currentTimeMillis() - time;
  124.             System.out.format("Elapsed time %dms %n", time);
  125.             if (result == ERROR) {
  126.                 System.out.format("Error compiling \"%s\"%n", expression);
  127.             } else {
  128.                 System.out.format("%s => %s%n", expression, result);
  129.             }
  130.         }
  131.     }
  132. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement