java - 如何在同一 JVM 中创建其他应用程序已加载的类的实例?

标签 java reflection

我在 Netbeans IDE 中创建了两个小型 Java 应用程序,比如说

App1 的类 First 如下

public class First{

  public static void main(String... str){
    First f = new First();
    System.out.print(f.getValue());
  }

  public int getValue(){
    return 10;
  }
}

并且App2具有Second类,如下

public class Second {
  public static void main(String... str){
    try{
      Class myClass = Class.forName("App1.First");
      Method m = myClass.getDeclaredMethod("getValue",new Class[] {});
      Object result = m.invoke(myClass,null);
      System.out.println(result);
    }catch(Exception e){
      System.out.println(e);
    }
  }
}

我在 Netbeans 中运行 App1.First,之后在 Netbeans 中运行 App2.Second。

OUTPUT: java.lang.ClassNotFoundException: App1.First

上面的代码不起作用。 我想从 App2.second 访问 App1.First 中的 getValue 方法。

I want to know whether we can create instance of class from other application and execute its methods on it in Java? If yes, then How?
Consider SecurityManager is not running.Please let me know where i have done mistake in code OR understanding concept.

我们将非常感谢您的回复。

Thanks for all the responses. If Netbeans runs each app in different JVM then May i know How we can run an Application in JVM in which other application is already running?

最佳答案

不,你不能。

每个应用程序都有自己的 JVM,有自己的类路径、加载的类等。您不能(在纯 Java 中)直接从另一个类访问一个 JVM 的类。

您需要做的是将 App1 的类放在 App2 的类路径上 - 有诸如 maven 之类的工具。帮助您设置这些依赖项。如果这样做,两个 JVM 都将拥有每个类的单独副本;您需要确保两个副本相同(例如,确保每次重新部署 App1 时都重新部署 App2)。您还需要设置某种方式让 JVM 相互通信:设置套接字或某种类似的方法,并使用双方都同意的序列化格式(序列化类、 protobufs 等)。

关于java - 如何在同一 JVM 中创建其他应用程序已加载的类的实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19637265/

相关文章:

java - 如何在 Java 应用程序中获取映射网络驱动器的 UNC 路径

c# - Method.Invoke 因参数计数不匹配而失败

java - 使用字段名称为对象设置字段(Java 反射)

go - Reflect showing different a different type than 错误

C# 从字符串中加载一个类型并声明一个列表

java - Context.CONNECTIVITY_SERVICE 错误。无法访问?

java - 将用户输入字符串中的数据添加到数组

java - 在 Java 中拆分多个分隔符

java - SOAP网络服务

c# - 使用反射以 IList<T> 形式检索 NHibernate.Collections.Generic.PersistentGenericBag