I'm brand new to Java. I have a question as follows:
class MyClass
{
public MyClass(String s){}
}
MyClass MyObject;
Constructor ctor1 = MyObject.class.getConstructor(String.class); // #1
Constructor ctor2 = MyObject.class.getConstructor(new Class[]{String.class}); // #2
What's the difference between #1 and #2?
There is no difference.
The parameter type of getConstructor() is Class<?>..., which employs the varargs syntax, which is syntactic sugar that automatically converts a list of elements of any size (including zero) to an array.
To illustrate, these two calls are equivalent:
Constructor ctor1 = MyObject.class.getConstructor(String.class, Integer.class); // #1
Constructor ctor2 = MyObject.class.getConstructor(new Class[]{String.class, Integer.class}); // #2
Although I admire your enthusiasm of "looking under the hood" (using reflection), if you are new to java you may consider holding off until you have a firm grasp of the basics before learning how to circumvent them.
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException
Have a look at defination of getConstructor(). It takes var-args parameter of type Class (Class<?> ...)
In your case, both the calls will eventually invoke the same constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With