用 Class.forName 和数组类型参数初始化一个类。

huangapple go评论73阅读模式
英文:

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(&quot;Wall&quot;).newInstance();

And if I want to pass Parameters through when I initiate the class, I can use

Constructor&lt;?&gt; c = Class.forName(&quot;Wall&quot;).getConstructor(param);

c.newInstance(Paramater values ie. &quot;String&quot;);

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&lt;?&gt; constr = Class.forName(&quot;Wall&quot;).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 );

huangapple
  • 本文由 发表于 2020年10月2日 00:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/64159805.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定