-1

So to explain my question, I would like to be able to write code inside a JTextField and with a press of a button my program would take that code, and execute it.

Is that even possible with normal java?

2
  • 1
    Yes, it's possible. You would use a JTextArea for the code. Commented Apr 14, 2022 at 16:37
  • Since a JTextField would basically only hold a single line of possible code. Commented Apr 14, 2022 at 16:39

2 Answers 2

0

You could save the contents of the text field to a file with the .java extension, then compile it and run the corresponding binary with Runtime.getRuntime().exec("javac " + [insert the name of your java file here]); and Runtime.getRuntime().exec("java " + [insert class name here]);. Though of course this wouldn't validate that the contents of the text field are valid java, nor would it work for any sufficiently complex code. For that, you'd basically be writing your own IDE, which is a task too complex to be discussed in a Stack Overflow answer.

Sign up to request clarification or add additional context in comments.

2 Comments

Fair enough, but is my question actually possible? Thanks for your answer!
As I explained, yes
0

Yes. Short outline:

  • Define an empty Class (implementing some Interface if you need parameters/feedback)
  • Put the text from the JTextArea into that class
  • Use a runtime compilation (javax.tools.ToolProvider.getSystemJavaCompiler();)
  • get the class via final URLClassLoader classLoader = new URLClassLoader(new URL[] { new File("./").toURI().toURL() });
  • load the class final Class<?> loadedClass = classLoader.loadClass(pFullClassName);
  • cast it into your interface
  • call the interface's methods on it
  • voilà

All in all it is hell to implement all that, took me 3 full days to have it working all in RAM without temporary files. Usually it's easier just to use some runtime container for JavaScript or something alike.

AND there may be probles, like when getting the compiler: it might not be present in your JVM. You'd have to run the code in a JDK, or add the Java Compiler jars to your classpath.

1 Comment

Thank you so much for the answer! I kind of expected it to be hard to implement, but I'll give it a try for sure!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.