举一个参数传递给主 [英] Give an arguments to main
问题描述
当我在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 tomain()
to the above string instead the one you provided.(2)
PersonneA
is subclass ofClassA
and not ofAlgo
- so after fixing issue 1 you will still get aClassCastException
, since an object of typePersonneA
is not of typeAlgo
这篇关于举一个参数传递给主的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!