Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between `String.class` and `new Class[]{String.class}`?

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?

like image 912
xmllmx Avatar asked Apr 25 '26 18:04

xmllmx


2 Answers

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.

like image 164
Bohemian Avatar answered Apr 27 '26 08:04

Bohemian


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.

like image 44
Ankur Shanbhag Avatar answered Apr 27 '26 07:04

Ankur Shanbhag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!