举一个参数传递给主 [英] Give an arguments to main

查看:114
本文介绍了举一个参数传递给主的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在args主给类的名称,一种说法是:
myPackage.Algo.PersonneA。我有一个例外,我不知道为什么?


  

异常线程main抛出java.lang.ClassNotFoundException:
  myPackage.Algo.PersonneA


这是我主要的:


 公共静态无效的主要(字串[] args){
        ALGO RF =(算法中)的Class.forName(参数[0])的newInstance()。    }


这是一类,我想主实例化。什么


  mypackage的包;
公共类算法中{
     公共静态类PersonneA扩展ClassA的{
        公共算法创建(INT R){
            返回新AlgorithmDist(新DistributedDocument(),R);
        }
    }    公共静态类PersonneB扩展ClassA的{
        公共算法创建(INT R){
            返回新AlgorithmSimul(新SimulationDocument(),R);
        }
    }
}



解决方案

两件事情:

(1)内部类,你需要传递给的forName()字符串:

 myPackage.Algo $ PersonneA
               ^
           代替 。

该内部类是从封装类分开了 $ ,而不是用
结果因此改变参数的main()上面的字符串,而不是您所提供的之一。

(2) PersonneA ClassA的的子类,而不是算法中的 - 因此修复问题1后,你仍然会得到一个 ClassCastException异常,因为类型的对象 PersonneA 是没有类型的算法中

When i give a name of Class in args to main , an argument is : "myPackage.Algo.PersonneA". I have an exception and i don't know why ?

Exception in thread "main" java.lang.ClassNotFoundException: myPackage.Algo.PersonneA

This is my main :

 public static void main(String[] args) {
        Algo rf = (Algo) Class.forName(args[0]).newInstance();

    }

and this is a class what i want instanciate in main.

package myPackage;
public class Algo {
     public static class PersonneA extends ClassA {
        public Algorithm create(int r) {
            return new AlgorithmDist(new DistributedDocument(), r);
        }
    }

    public static class PersonneB extends ClassA {
        public Algorithm create(int r) {
            return new AlgorithmSimul(new SimulationDocument(), r);
        }
    }
}

解决方案

Two things:

(1) for inner class, you need to pass to forName() the string:

"myPackage.Algo$PersonneA"
               ^
           instead of .

The inner class is seperated from the enclosing class with a $ and not with a ..
So change the argument to main() to the above string instead the one you provided.

(2) PersonneA is subclass of ClassA and not of Algo - so after fixing issue 1 you will still get a ClassCastException, since an object of type PersonneA is not of type Algo

这篇关于举一个参数传递给主的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆