在运行时,在我的 Java 程序中,给定一个字符串,我想知道返回类型。例如:
1 + 1
返回int
1L + 1L
返回long
1L + 1
返回long
1 + 1.5
返回double
1 + 2 - 3 * 4 / 5
返回int
1 / 0
返回int
1 + Math.nextInt()
返回int
1.5 + Math.nextInt()
返回double
Color.RED
返回java.awt.Color
- 鉴于这
a
是一个 int:a + 1
返回int
- 鉴于这
a
是一个 int:a + 1.5
返回double
无需实际评估代码:我只需要返回类型。如何使用 JDK 运行时编译器、ECJ JDT 或任何其他纯 Java 依赖项来做到这一点?
详细代码:这是此代码的简化伪代码单元测试:
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"}));
}
}