1

I have a text file that contains java codes, without main method, for example :

System.out.println("Hello Word");
...

Im looking for a way to run these codes, without using Runtime.getRuntime().exec

is that possible with java reflection or any thing else?

  • 1
    Reflection is for existing code, not for text. Also `exec` can run a compiled jar, not a text file with main missing – azro Jul 16 '18 at 11:13
  • Can you specify what exactly you want to achieve? For example there is [Service Loader](https://docs.oracle.com/javase/9/docs/api/java/util/ServiceLoader.html) that allows discovery of "services" during runtime. This allows you to find and execute any code that was provided (compiled version, implementing your Service). Also since this was closed as duplicate you should specify why is this question different if you intend to continue. – Piro Jul 16 '18 at 11:27

1 Answers1

0

Create a dummy class with a placeholder as a variable:

private static final String DUMMY_CLASS = 
    "public class Dummy {\n"+
    "    public static void main(String[] args){\n"+
    "       /* PLACEHOLDER */\n"+
    "    }\n"+
    "}";

And then just read your text file and replace the /* PLACEHOLDER */ text within the variable with the contents of the text file.

At last write the newly created class to a java file and compile it.

On How you do all these steps: Those are easy findable on the internet and are just some hints on how to do it.

Lino
  • 19,604
  • 6
  • 47
  • 65
  • Not all text will work with this template. If text will be for example `System.out.println(new Date())`, you need `import java.util.Date` line at top – alaster Jul 16 '18 at 11:21
  • @alaster of course. One way would also be to define the imports in the text file itself but this would require some form of parsing, which my current solution does not support – Lino Jul 16 '18 at 11:23