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 ?

+3


source to share


4 answers


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.

+6


source


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.

+2


source


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.

0


source


string #1

will call the first constructor
string #2

will call the second

public class MyObject {

  public MyObject(String arg) {
    // ...
  }

  public MyObject(String[] args) {
    // ...
  }

}

      

-1


source







All Articles