Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

java - Initializing a class with Class.forName() and which have a constructor which takes arguments

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...