给 main 一个参数 [英] Give an arguments to main

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

问题描述

当我在 args 中给 main 一个 Class 的名字时,一个参数是:myPackage.Algo.PersonneA".我有一个例外,我不知道为什么?

<块引用>

线程main"中的异常java.lang.ClassNotFoundException:myPackage.Algo.PersonneA

这是我的主要内容:

<块引用>

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

这是我想要在 main 中实例化的类.

<块引用>

package myPackage;公共类算法{公共静态类 PersonneA 扩展了 ClassA {公共算法创建(int r){返回新的 AlgorithmDist(new DistributedDocument(), r);}}公共静态类 PersonneB 扩展了 ClassA {公共算法创建(int r){返回新的 AlgorithmSimul(new SimulationDocument(), r);}}}

解决方案

两件事:

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

"myPackage.Algo$PersonneA"^代替 .

内部类与封闭类用 $ 而不是 . 分开.
因此,将 main() 的参数更改为上述字符串,而不是您提供的字符串.

(2) PersonneAClassA 的子类而不是 Algo - 所以在修复问题 1 之后你仍然会得到一个 ClassCastException,因为 PersonneA 类型的对象不是 Algo

类型

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

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

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