How to create a method out of the text file?

扶醉桌前 提交于 2019-12-23 06:13:34

问题


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?


回答1:


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.




回答2:


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.


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.




回答3:


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



回答4:


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

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




回答5:


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



来源:https://stackoverflow.com/questions/8080799/how-to-create-a-method-out-of-the-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!