javareflectionruntime-compilationecj

Determine return type of a Java expression in a String at runtime


At runtime, in my Java program, given a String, I 'd like to know the return type. For example:

There is no need to actually evaluate the code: I just need the return type. How can I do this with the JDK runtime compiler, ECJ JDT or any other pure Java dependency?


Detailed code: Here's a simplified, pseudo-code unit test for this code:

public static void ExpressionTyper {
    public String determineType(String expression, Map<String, String> variableTypes) {
       ... // How do I implement this?
    }
}
public void ExpressionTyperTest {
    @Test public void determineType() {
        assertEquals("int", ExpressionTyper.determineType("1 + 1", emptyMap());
        assertEquals("long", ExpressionTyper.determineType("1 + 1L", emptyMap());
        assertEquals("double", ExpressionTyper.determineType("1 + 1.5", emptyMap());
        assertEquals("int", ExpressionTyper.determineType("a + 1", mapOf({"a", "int"}));
        assertEquals("int", ExpressionTyper.determineType("a + b", mapOf({"a", "int"}, {"b", "int"}));
        assertEquals("double", ExpressionTyper.determineType("a + b", mapOf({"a", "double"}, {"b", "int"}));
    }
}

Solution

  • I think this depends on the range of input you want to be able to process.

    You see, in the end you are asking: how do I evaluate string expressions at runtime.

    So, the short answer is: you need some kind of interpreter / REPL implementation; or at least "parts" of that.

    Another approach could be to use the javax compiler to simply compile the thing, and then deduce the type, like here.

    Other options would go along the lines of certain "compiler construction" topics, like constant folding.