0

I want to parse a method stored in a string variable, for example:

"public void printStr(String arg) { System.out.println("Method called"); } "

and convert this into a java.lang.reflect.Method object.

How can I do this?

David Buck
  • 3,752
  • 35
  • 31
  • 35
  • 2
    You won't be able to directly convert it into a `Method`. If you want a `Method` then you'll have to compile the source first, which means fully valid Java. Or you could try using the [JShell API](https://docs.oracle.com/en/java/javase/15/docs/api/jdk.jshell/module-summary.html). – Slaw Dec 29 '20 at 05:11
  • A method needs a class to live in. Is it OK if you include the enclosing class? The method may be static or not – Bohemian Dec 29 '20 at 09:57
  • Hi @Bohemian it is fine if i include method inside enclosing class. Do you have any solution for that? – Sarang Saraf Dec 30 '20 at 09:09
  • 1
    See [`JavaCompiler`](https://docs.oracle.com/en/java/javase/15/docs/api/java.compiler/javax/tools/JavaCompiler.html) and [`ClassLoader`](https://docs.oracle.com/en/java/javase/15/docs/api/java.base/java/lang/ClassLoader.html). Also see [How to compile and run java source code in memory](https://stackoverflow.com/questions/31599427/how-to-compile-and-run-java-source-code-in-memory). – Slaw Dec 30 '20 at 09:44
  • 2
    Build your class def as a string, then compile it in memory and load it using the class loader. I have used Janino with success. Javassist also seems popular. – Bohemian Dec 30 '20 at 11:27

0 Answers0