-1

I have dynamic set of string expressions(java code parts) eg :

val1.subtract(val2.divide(val3,6,java.math.RoundingMode.HALF_UP) ,new MathContext(6, java.math.RoundingMode.HALF_UP)).setScale(6, BigDecimal.ROUND_HALF_UP)

I want to extract variable names from each expression using java. For above example, output should be:

[val1,val2,val3]

How do I address this issue?

note :

varible names could be any java accepted ones. No any patterns

Nilanka Manoj
  • 3,527
  • 4
  • 17
  • 48

1 Answers1

2

A string which forms a valid java expression requires a complete java parser, capable of parsing every aspect of the entire java language.

This is a valid expression:

new Object() {
    public int test() {
        return 5;
    }
}.test();

Its type is int, and it would evaluate to 5.

You can write anything inside those braces. Including new types.

Thus, there are only two answers available:

  • Define a restricted set of operations, which means you no longer have 'a java expression', but, a 'NilankaManoj expression'. You'd have to write the spec: Which bits are and are not allowed? Without that spec, your question isn't answerable.
  • Alternatively, you really do want any java expression, in which case, search the web for an open source java parser. Various parser libraries such as ANTLR 'ship' with a java grammar which is usually out of date and not quite complete. Alternatively, get ecj which is open source. All of these are complex beasts with a very significant learning curve.
rzwitserloot
  • 85,357
  • 5
  • 51
  • 72