How to execute the java method from text?
已回答
PsiFile fileFromText = PsiFileFactory.getInstance(project).createFileFromText(JavaLanguage.INSTANCE, "public class Test {public String aa() {return \"123\";}}");
PsiJavaFile psiJavaFile = (PsiJavaFile)fileFromText;
PsiMethod targetMethod = psiJavaFile.getClasses()[0].getMethods()[0];
The above code, I can get PsiMethod from method aa, if I want execute the aa method and get the result of it? How should I do?
Could you give some code example?
请先登录再写评论。
Maybe I need to describe how to compile a text and execute the method from the text
Hi,
In general, you will need to compile a class containing a
main
method and run the compiled code from themain
method. There is no API that allows running a piece of code from a text (Java is not a scripting language).You can find a javac.jar, then compile the code, create a class through reflection, and call the aa method