This could well be a stupid question, but I’m new to Java, so…
I’ve currently got some code where currently this is being used
clazz.asSubclass(asSubclassOfClass).getConstructor().newInstance()
I need to pass some arguments to the contructort so I want to change it to: clazz.asSubclass(asSubclassOfClass).getConstructor(params).newInstance(args)
What I don’t understand is what I need to pass in as params and what I need to pass in as args.
Let’s say I wanted to pass in a String “howdy” and some object of type XYZ called XyzObj in. How would I specify that? WHat would I pass as params and what would I pass as args?
In Java this is called Reflection.
Assuming the class has this constructor, otherwise you will get a NoSuchMethod exception I believe.
Since you are new to Java, let me give you an easier so that you can understand what’s going on under the hood when you do this.
Assume you have the following class:
Then you have the following main method:
If you run this you will notice the console output print message – I have been invoked. This means that using reflection you have invoked the constructor of ParentClazz.
You can do the same thing if the scenario allows you is by using standard object creation process:
Hope this helps you understand it.