2

I have an application that has stored various classes in string form. For example, I might have this class:

public class HelloWorld {
public static void main(String[] args) {
    System.out.println("Hello, World!"); 
}

that is stored as a string in a database. I would like to know whether this string contains a class that can compile successfully. How would I go about doing that? Is there a package for this?

Peter Lo
  • 29
  • 2
  • 1
    IMO, the validation should be done before it is stored into the database... – YUNG FOOK YONG Oct 10 '22 at 10:53
  • 1
    You can use the [Java compiler API](https://docs.oracle.com/en/java/javase/17/docs/api/java.compiler/module-summary.html) for this. But this is not something that's super easy to use. – Jesper Oct 10 '22 at 11:00
  • 1
    Not an *exact* duplicate, but [check this out](https://stackoverflow.com/questions/4463440/compile-java-source-code-from-a-string) – Federico klez Culloca Oct 10 '22 at 11:01

1 Answers1

-1

Create a text file and write the code to the file using Java:

FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("public class HelloWorld {
public static void main(String[] args) {
    System.out.println("Hello, World!"); 
}");
myWriter.close();

Now run the file via

String[] args = new String[] {"/bin/bash", "-c", "your_command", "with", "args"};
Process proc = new ProcessBuilder(args).start(); 

You'll get to know if it compiles from its return value.

Ananthu K Kumar
  • 86
  • 2
  • 10
  • 1
    How would that prove it can compile successfully? – Federico klez Culloca Oct 10 '22 at 10:55
  • Well this obviously requires lots of debugging, but at first you can take string and run a process in cmd from your appn itself. If it runs obviously it compiles, you can google the code for running the process. – Ananthu K Kumar Oct 10 '22 at 15:37
  • I'll be honest, I still don't understand your answer. They're asking how to check whether a string represent compilable code and you tell them to do string comparisons on the source code. So again, how do those comparison prove anything about the fact that the code in the string itself compiles? – Federico klez Culloca Oct 10 '22 at 17:16
  • Okay I misunderstood, but how about you write this string to a text file and compile that file in terminal or cmd. – Ananthu K Kumar Oct 11 '22 at 13:00