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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use
Class.getConstructor()and callConstructor.newInstance()on that. For example if this is your constructor on classFoo:You’d have to do something like this:
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.