What's the difference between `String.class` and` new Class [] {String.class} `?
I am new to Java. I have a question:
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 is the difference between # 1 and # 2 ?
source to share
There is no difference.
The parameter type is getConstructor()
- Class<?>...
, which uses varargs , which is syntactic sugar that automatically converts a list of elements of any size (including zero) to an array.
For illustration, 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
While I admire your enthusiasm for "looking under the hood" (using reflection), if you are new to java you might consider holding on until you have a solid understanding of the basics before learning how to work around them.
source to share
public Constructor<T> getConstructor(Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException
Take a look at defination getConstructor()
. It takes a var-args parameter of typeClass (Class<?> ...)
In your case, both calls will end up calling the same constructor.
source to share
Not from a functional point of view.
The getConstructor method has the signature varargs, where you can specify a variable number of parameters. Internally Java converts this parameter list to an array, so the signature with varargs is the same as the signature with an array of that type.
Your ctor1 is using the varargs' version of the signature, while your ctor2 is using the 'version' array.
source to share