1

Let's say we have a program with a method void foo(int a, int b, int c), and we have a list of statements given in string formats like "System.out.println(a);" or "int q = a+b+c;" or "try{int d = a/b;}catch(Exception e){}". Is there a convenient way to insert these statements into foo using Java Parser?

Note that the statements are given in string format and we do not know beforehand what the statements are, so it seems extremely hard to build the statement up using BlockStmt, NameExpr, FieldExpr, etc. because that would require parsing the statement string into these fields. Is there any way Java Parser can add the string-formatted statements without needing me to write a statement string parser?

Yiwei Lyu
  • 23
  • 3
  • Well, the fundamental question here is what is your code and what is your data. Normally, code is something compiled ONCE and then used in binary form. DATA is something that changes and is consumed at runtime. It is unclear where this boundary exists given your question. If most of your data is Java code, why not have it all be and just modify an entire "program" when your data changes...that is, compile everything every time. If you want something other than this, then you're talking about two executions of the "java parser" and you're into the complex world compiling code from code. – CryptoFool Feb 23 '19 at 21:57
  • If you mean. "Can I compile a program that defines foo() and THEN somehow use the java parser to change the binary for that method?", the answer is NO. What you could do is subclass the object containing foo() by generating new code, and then compiling the COMPLETE description of that new object into a new binary from within your first binary. And then your first binary would presumably run the second binary. This is a super complex question. There are all sorts of ways of running generated code. None of them are trivial. – CryptoFool Feb 23 '19 at 21:59
  • You could also presumably compile a snippet of code and then splice it into an existing object with introspection. This is hard though. The Java parser wouldn't do this for you. Maybe you're looking for the equivalent of an "eval" function found in interpreted languages. This doesn't exist in Java, or in compiled languages in general. This post may help you: https://stackoverflow.com/questions/2605032/is-there-an-eval-function-in-java – CryptoFool Feb 23 '19 at 22:09
  • Actually...with my first suggestion, you wouldn't necessarily have to "run the second binary". If you compiled a new .class object, you could cause the Java runtime, via a ClassLoader, to load just that new object into the existing running binary. This also is not trivial though. - Per the post I gave you above, maybe Java just isn't the right language for what you want to do. You might instead use something like Javascript, or Python – CryptoFool Feb 23 '19 at 22:16
  • @Steve Thanks! That was very helpful. – Yiwei Lyu Feb 24 '19 at 22:05

0 Answers0