Search code examples
javassistbyte-buddy

How to convert dynamically input user expression to java code?


I read the byte buddy and javassist doc and I would like do not know if is possible to convert a string like:

get foos where name == toto

to

data.getFoos().stream()
              .filter( f -> f.name.equals( "toto" ) )
              .collect( Collectors.toSet() )

A regex could capture the expression as:

final Pattern query = Pattern.compile("get (\\w+) where (\\w+) ([=!]+) (\\w+)");
final Scanner scanner = new Scanner(System.in);
final Matcher matcher   = query.matcher(input);
matcher.group(1) // foos -> Foo and foos -> getFoos()
matcher.group(2) // field to use as filter
matcher.group(3) // symbol == / !=
matcher.group(4) // thing to match
  1. convert get foos to getFoos()
  2. check from Foo class if name field exists
  3. if fields name is not an instance of Number.class translate == to .equals
  4. make the expression
  5. loop and print results

I read some examples without able to found a such thing. So I come here to get your light. thanks


Solution

  • Both Byte Buddy and Javassist generate byte code, not Java code. Javassist does however have functionality to translate String-contained source code to byte code from your inputs. However, the source code level is at Java 4 level such that you cannot use lambdas.

    I do however wonder if this is the correct approach for your problem. Rather, I would suggest you to programmatically resolve a stream from the arguments. You could amplify this by creating a custom aPI to transform your arguments into the stream in question.