Question

I have a text (.txt) file that contains Java code! I want to create a method that includes this Java code and then call that method through the program.

Can anybody suggest a way to do this?

Was it helpful?

Solution

let consider this example what it does actually load the source code, compile and execute the java code by simpler program by using JavaCompiler API.

OTHER TIPS

Use the JavaCompiler. It can compile code from a String, so I'm sure it could handle code from a text file.


Do you think instead of putting it in the main method I can put it in for example test method and call method like this?

Put it wherever you like. E.G. see the STBC & especially the source code. It provides a GUI and can compile the code in the text area on button click.

STBC GUI


this program need tools.jar but jre 7 doesnt have this!!

Did you try reading the documentation that is provided for the STBC? Notably:

System Requirements

STBC will run on any computer with a version 1.6+ Java Plug-In* JDK (AKA SDK).

(*) The API that STBC uses is merely a public interface to the compiler in the tools.jar that is distributed only with JDKs (though the 'public JRE' of the JDK also seems to acquire a tools.jar). This leads to some unusual requirements in running either the native jar, or the web start app.


Or shorter, no JRE will have a JavaCompiler, only JDKs have them.

  1. Change the .txt file to a .java file,
  2. add it to your java project
  3. Compile the code
  4. Execute the methods

Load the file in through standard java IO and then have Groovy evaluate it for you:

http://groovy.codehaus.org/Embedding+Groovy

it's something like quine: http://www.nyx.org/%7Egthompso/quine.htm

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top