在运行时重新编译对象

问题描述:

我正在开发一个java项目,其中运行主文件后,一些java文件被修改,如果我在同一执行过程中再次运行该文件,输出不会显示在java中完成的更改文件在运行时重新编译对象

例如有2个文件。 Main.java和file1.java

main.java

public static void main(string[] argv) 
{ 

    file1 obj = new file1(); 
    obj.view(); 
     Scanner in = new Scanner(System.in); 
     String x = in.nextLine(); 
    //before entering any value i manually updated the content of file1.java 
    obj = new file1(); 
    obj.view(); 
} 

file1.java(更新用前)

public class file1 
{ 

    public void view() 
    { 

     system.out.println("This is test code!!"); 
    } 


} 

file1.java(更新用后)

public class file1 
{ 

    public void view() 
    { 

     system.out.println("That was done for Testing!!"); 
    } 


} 

Output : 
This is test code!! 

This is test code!! 
+0

Java在语言级别没有解释,它被编译为字节码。修改源代码意味着它必须重新编译 – maress

+1

即时修改源代码是一项高级技术。这听起来不像是你的意图,当然也不是你提供的例子所必需的。你想达到什么目的? – GoZoner

您必须重新编译代码才能看到更改。

你可以做的是用java编译一个字符串(在从文件中读取之后),并通过反射调用类的方法。

HERE是如何以编程方式编译字符串的分步指南。

更新Java文件不会影响JVM执行的运行时指令。

编译Java应用程序时,.java源代码文件被编译为包含字节码指令的.class文件,而这些指令又由JVM解释。当JVM需要一个类时,它通过一个称为类加载器的特殊对象将相应的.class文件加载到内存中。

将此应用于您的示例 - 当您首次引用类File1时,JVM会将File1类加载到内存中。这个在类的内存表示中将一直存在,直到类加载器被销毁或JVM重新启动。 JVM没有对file1.java类进行任何更改 - 首先是因为类加载器不会重新加载定义,其次是因为在重新编译file1.java类之前定义不会更改。

要在运行时更改对象的行为,可以使用反射API,请参阅here

你不需要编译源代码来完成任何接近你的例子的东西。

public class MyView 
{ 
    String the_string; 
    public MyView (String string) { the_string = string; } 
    public void setString (String string) { the_string = string; } 
    public void view() { system.out.println (the_string); } 
} 

public static void main(string[] argv) 
{ 

    MyView obj = new MyView("This is test code!!"); 
    obj.view(); 
     Scanner in = new Scanner(System.in); 
     obj.setString (in.nextLine()); 
    obj.view(); 
}