用Class.forName()初始化一个类,并且有一个构造函数接受参数 [英] Initializing a class with Class.forName() and which have a constructor which takes arguments
问题描述
我正在实例化一个这样的类。
myObj =(myObj)Class.forName(完全限定类名).newInstance();
我的怀疑是,如果我们有一个构造函数需要参数,如何像上面一样实例化。谢谢,
Narendra
使用 Class.getConstructor()
,并调用 Constructor.newInstance()
on那。例如,如果这是您的类 Foo
上的构造函数:
public Foo (String bar,int baz){
}
你必须做一些像这个:
构造函数c = Class.forName(Foo)。getConstructor(String.class,Integer.TYPE);
Foo foo =(Foo)c.newInstance(example,34);
你必须知道需要传递给构造函数的参数。如果这是不可取的,你应该考虑有一个空的构造函数。然后有方法来设置通常传递给构造函数的方法。
可能会问你是否有正确的模式。你真的需要使用反思,也许有更好的方法吗?如果你知道你将要投射到你的对象,为什么不正常地构建它?您可能希望提供更多的上下文,了解您为什么需要这样做。有正当理由,但您没有说明任何。
I am instantiating a class like this.
myObj = (myObj) Class.forName("fully qualified class name here").newInstance();
My doubt here is if we have a constructor which takes arguments how can we instantiate it like above one.
Thanks,
Narendra
Use Class.getConstructor()
and call Constructor.newInstance()
on that. For example if this is your constructor on class Foo
:
public Foo(String bar, int baz) {
}
You'd have to do something like this:
Constructor c = Class.forName("Foo").getConstructor(String.class, Integer.TYPE);
Foo foo = (Foo) c.newInstance("example", 34);
You'll have to know what arguments need to be passed to the constructor. If that's not desirable you should consider having an empty constructor. Then have methods to set what you'd normally pass into the constructor.
One might ask if you have the right pattern here though. Do you really need to use reflection, perhaps there's a better approach? If you know you're going to be casting to your object already, why not just construct it normally? You might want to provide more context as to why you need to do this. There are valid reasons, however you haven't stated any.
这篇关于用Class.forName()初始化一个类,并且有一个构造函数接受参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!