1/*
2 * Copyright (c) 2005, 2006, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24package evalexpr;
25
26import java.lang.reflect.Method;
27import java.util.*;
28import javax.swing.JOptionPane;
29import javax.tools.*;
30import static javax.tools.StandardLocation.CLASS_OUTPUT;
31
32/**
33 * JSR 199 Demo application: compile from a String.
34 *
35 * <p><b>This is NOT part of any supported API.
36 * If you write code that depends on this, you do so at your own
37 * risk.  This code and its internal interfaces are subject to change
38 * or deletion without notice.</b></p>
39 *
40 * @author Peter von der Ah&eacute;
41 */
42public class CompileFromString {
43
44    /**
45     * The name of the class used to evaluate expressions.
46     */
47    private final static String CLASS_NAME = "EvalExpression";
48
49    /**
50     * Object used to signal errors from evalExpression.
51     */
52    public final static Object ERROR = new Object() {
53        public String toString() { return "error"; }
54    };
55
56    /**
57     * Compile and evaluate the specified expression using the
58     * given compiler.
59     * @param compiler a JSR 199 compiler tool used to compile the given expression
60     * @param expression a Java Programming Language expression
61     * @return the value of the expression; ERROR if any errors occured during compilation
62     * @throws java.lang.Exception exceptions are ignored for brevity
63     */
64    public static Object evalExpression(JavaCompiler compiler,
65                                        DiagnosticListener<JavaFileObject> listener,
66                                        List<String> flags,
67                                        String expression)
68        throws Exception
69    {
70        // Use a customized file manager
71        MemoryFileManager mfm =
72            new MemoryFileManager(compiler.getStandardFileManager(listener, null, null));
73
74        // Create a file object from a string
75        JavaFileObject fileObject = mfm.makeSource(CLASS_NAME,
76            "public class " + CLASS_NAME + " {\n" +
77            "    public static Object eval() throws Throwable {\n" +
78            "        return " + expression + ";\n" +
79            "    }\n}\n");
80
81        JavaCompiler.CompilationTask task =
82            compiler.getTask(null, mfm, listener, flags, null, Arrays.asList(fileObject));
83        if (task.call()) {
84            // Obtain a class loader for the compiled classes
85            ClassLoader cl = mfm.getClassLoader(CLASS_OUTPUT);
86            // Load the compiled class
87            Class compiledClass = cl.loadClass(CLASS_NAME);
88            // Find the eval method
89            Method eval = compiledClass.getMethod("eval");
90            // Invoke it
91            return eval.invoke(null);
92        } else {
93            // Report that an error occured
94            return ERROR;
95        }
96    }
97
98    /**
99     * Main entry point for program; ask user for expressions,
100     * compile, evaluate, and print them.
101     *
102     * @param args ignored
103     * @throws java.lang.Exception exceptions are ignored for brevity
104     */
105    public static void main(String... args) throws Exception {
106        // Get a compiler tool
107        final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
108        final List<String> compilerFlags = new ArrayList();
109        compilerFlags.add("-Xlint:all"); // report all warnings
110        compilerFlags.add("-g:none"); // don't generate debug info
111        String expression = "System.getProperty(\"java.vendor\")";
112        while (true) {
113            expression = JOptionPane.showInputDialog("Please enter a Java expression",
114                                                     expression);
115            if (expression == null)
116                return; // end program on "cancel"
117            long time = System.currentTimeMillis();
118            Object result = evalExpression(compiler, null, compilerFlags, expression);
119            time = System.currentTimeMillis() - time;
120            System.out.format("Elapsed time %dms %n", time);
121            if (result == ERROR)
122                System.out.format("Error compiling \"%s\"%n", expression);
123            else
124                System.out.format("%s => %s%n", expression, result);
125        }
126    }
127}
128