java - RMI客户端方法调用

标签 java compiler-errors rmi

我是 RMI 新手,并尝试将以下内容应用到我正在开发的项目中。
这段代码 Naming.lookup......theWork.newCalculator(); 是否总是需要在 main 方法中?
我可以在 main 方法之外调用 myCalculator 吗?
当我尝试时,我收到 myCalculator 无法解析 错误。
下面的示例在 main 中调用 myCalculator,因此它可以工作。如何使 myCalculator.plus(arg) 在另一种方法中可用?

public static void main(String [] args)
{

        try{


            CalculatorFactory theWorks =     (CalculatorFactory)Naming.lookup("rmi://localhost:13456/CalculationsAnon");
            Calculator myCalculator = theWorks.newCalculator();

            System.out.println("I have a calculator");

            int val = 0;
            myCalculator.clear();
            BufferedReader bin = new BufferedReader(new InputStreamReader(System.in));
            for(;;)
            {
                System.out.println(": "+val+":");
                System.out.print("Command>");
                String s = (bin.readLine().trim());

                if(s.equals("+")){

                    System.out.print("Value>");
                    int arg = 0;
                    s=(bin.readLine().trim());
                    arg = Integer.parseInt(s);
                    val = myCalculator.plus(arg);

                }

                // more codes here

最佳答案

您已将 myCalculator 对象定义为 main 方法内的局部变量,这就是为什么如果您尝试在外部引用它,则会出现无法解析错误。

您是否尝试在主方法之外定义 myCalculator 对象引用,如下所示:-

private static Calculator myCalculator = null;

public static void main(String [] args)
{

        try{


            CalculatorFactory theWorks =     (CalculatorFactory)Naming.lookup("rmi://localhost:13456/CalculationsAnon");
            myCalculator = theWorks.newCalculator();

           // You rest of the code here

关于java - RMI客户端方法调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25590409/

相关文章:

java - 从 JUnit 4 转换到 TestNG。如何处理参数?

c++ - 转换为 std::thread 状态调用私有(private)构造函数

ssl - 如何在docker中的应用程序上设置远程访问SSL JMX接口(interface)

java - 连接到 Websphere rmi 服务器

java - RMI ClassNotFoundException 异常

java - 我需要将时间显示为 24 小时格式到 12(上午/下午)小时格式

java - 如何通过Java驱动在MongoDB中创建复合索引?

java - 前端Java,后端C++,如何加入?

gcc - GCC 4.5 : “checking whether the C compiler works… no” error when CFLAGS =“-arch x86_64”

java - 参数数组字符串Jframe