且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

给 main 一个参数

更新时间:2023-01-08 15:58:23

两件事:

(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