java – `String. What is the difference between class’ and ‘new class [] {string. Class}’?

I'm 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?

Solution

No difference

The parameter type getconstructor() is class , It adopts varargs syntax, which is a syntax sugar, which can automatically convert a list of elements of any size (including zero) into 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

Although I admire your enthusiasm for "thinking" (using reflection), if you are new to Java, you can consider waiting until you have a firm grasp of the basics before learning how to avoid them

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>