英文:
Initialize A Class by Class.forName with Array type parameters
问题
我有一个带有构造函数的类,我需要通过名称进行初始化。
public class Wall extends Tile
{
public Wall(double x, double y, double[] data)
{
super();
}
}
Tile是一个抽象类,它的构造函数是空的。
我可以使用以下方式初始化这个类:
Class.forName("Wall").newInstance();
如果我想在初始化类时传递参数,我可以使用以下方式:
Constructor<?> c = Class.forName("Wall").getConstructor(param);
c.newInstance(参数值,例如 "String");
至于`param`,它取决于您要传递的参数类型。
`int`:`Integer.TYPE`
`double`:`Double.TYPE`
`String`:`String.class`
这篇stackoverflow上的帖子对我理解这些参数有所帮助
https://stackoverflow.com/questions/5658182/initializing-a-class-with-class-forname-and-which-have-a-constructor-which-tak
但我有一个问题,我怎么传递数组参数,比如`double[]`?
我尝试过`Double[].class`,但那会抛出`ThreadNotFoundException`错误。
任何帮助将不胜感激。
英文:
I have a class with a constructor that I need to initialize by name.
public class Wall extends Tile
{
public Wall(double x, double y, double[] data)
{
super();
}
}
the Tile is an abstract class, and it's constructor is empty.
I can initialize this class with
Class.forName("Wall").newInstance();
And if I want to pass Parameters through when I initiate the class, I can use
Constructor<?> c = Class.forName("Wall").getConstructor(param);
c.newInstance(Paramater values ie. "String");
As for the param
, it depends on what type of parameter you are passing through.
int
: Integer.TYPE
double
: Double.TYPE
String
: String.class
this post on stackoverflow helped me with those parameters
https://stackoverflow.com/questions/5658182/initializing-a-class-with-class-forname-and-which-have-a-constructor-which-tak
But the question I have is how can I pass through Array parameters. ie a double[]
?
I've tried Double[].class
, but that threw a ThreadNotFoundException
.
Any help would be appreciated.
答案1
得分: 1
可能有更好的方法。但我已经测试过了,它可以工作:
Constructor<?> constr = Class.forName("Wall").getDeclaredConstructor(Double.TYPE, Double.TYPE, (new double[] {}).getClass());
double x = 1;
double y = 2;
double[] data = new double[] {1, 2, 3, 4};
Wall obj = (Wall) constr.newInstance(x, y, data);
英文:
It might there be a better way. But I've tested that and it works:
Constructor<?> constr = Class.forName("Wall").getDeclaredConstructor(Double.TYPE, Double.TYPE, (new double[] {}).getClass());
double x = 1;
double y = 2;
double[] data = new double[] {1, 2, 3, 4};
Wall obj = (Wall) constr.newInstance( x , y, data );
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论