英文:
How can I write and use a Java file in the same runtime
问题
我正在尝试使这个程序在同一运行时编写Ran.java文件并使用它。但由于文件尚未创建,Java错误检查会阻止我在代码中创建它的对象。有没有办法使文件能够在同一运行中被写入和使用?
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
class Main {
public static void main(String[] args) {
try {
File myObj = new File("Ran.java");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
FileWriter my = new FileWriter("Ran.java");
my.write(""
+ "import java.util.Random;\n"
+ "class Ran {\n"
+ " Random ran = new Random();\n"
+ " int makeRint(int N, int M) {\n"
+ " int a = ran.nextInt(M + N - 1) + N;\n"
+ " return a;\n"
+ " }\n"
+ "}\n");
my.close();
run();
} else {
run();
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static void run() {
Ran a = new Ran();
System.out.println(a.makeRint(1, 35));
}
}
如果我删除Ran对象的实例化和对其US方法的调用,我可以运行该文件并在之后添加它,但我不想手动编辑.java文件。即使有一种方法在第二次运行时运行Ran.java文件而不编辑Main.java,那将会很好。
英文:
I am trying to make this program write the Ran.java file and us it in the same run time. But because the file is not made yet the java error checking is making it so I can not make a object of it in my code. Is there a way to make it so the file can be wrighten and used in the same run?
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
class Main {
public static void main(String[] args) {
try {
File myObj = new File("Ran.java");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
FileWriter my = new FileWriter("Ran.java");
my.write("""
import java.util.Random;
class Ran {
Random ran = new Random();
int makeRint(int N, int M){
int a = ran.nextInt(M + N - 1) + N;
return a;
}
}
""");
my.close();
run();
}
else {
run();
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
public static void run(){
Ran a = new Ran();
System.out.println(a.makeRint(1, 35));
}
}
If I take out the instantiation of the Ran object and the call to it's US method I am able to run the file and add it in after, but I don't want to edit the .java file manuely. Even if there is a way to run the Ran.java file on the secound run through without editing Main.java that would be great.
答案1
得分: 1
你不能这样做,因为Java不是一种解释性语言。你必须首先将源代码编译成字节码,然后使用Java运行时执行字节码。如果这对你有用,那么你可以通过使用Java编译器API来以编程方式执行此操作,然后动态加载JAR文件中的类。你可以搜索这个主题,应该会有很多答案。
英文:
You can not because Java is not an interpreted language. You have to compile first the source code into bytecode, then execute the bytecode with the Java runtime. If that works for you then you could do that programmatically, by using the Java Compiler API then loading the classes in a JAR file dynamically. You can search for that topic, there should be plenty of answers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论