RMI客户端方法调用

时间:2014-08-31 08:52:55

标签: java compiler-errors rmi

我是RMI的新手并尝试将以下内容应用到我正在处理的项目中。
这段代码Naming.lookup...... theWork.newCalculator();是否总是需要采用main方法? 我可以在myCalculator方法之外拨打main吗? 当我尝试时,我收到myCalculator cannot be resolved错误 下面的示例在myCalculator中调用main,因此可行。如何在另一种方法中提供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

2 个答案:

答案 0 :(得分:1)

您已将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

答案 1 :(得分:0)

  

这段代码是否是“Naming.lookup ...... theWork.newCalculator();”总是需要在主方法?

没有

  

我可以在main方法之外调用myCalculator吗?

是的,只要您有权访问theWorks变量。

  

当我尝试时,我收到myCalculator cannot be resolved错误。

这是编译错误。提到的变量不在范围内。它根本与RMI毫无关系,只是一个常见的编程错误。

  

下面的示例在main中调用myCalculator,因此它可以正常工作。如何在另一种方法中使myCalculator.plus(arg)可用?

在该方法中执行查找,或将main方法查找的结果存储到静态或实例变量而不是局部变量中。

相关问题