[]) Null)"? I am trying to understand this difference with t...">

What is the difference between "getConstructor ()" and "getConstructor ((Class <?> []) Null)"?

I am trying to understand this difference with this example:

import java.lang.reflect.*;
public class ClassDemo {

   public static void main(String[] args) {
     try {
        // returns the Constructor object of the public constructor
        //Class cls[] = new Class[] { String.class };
        Constructor c = String.class.getConstructor();
        System.out.println(c);
     }
     catch(Exception e) {
        System.out.println(e);
     } 
   }
} 

I get this result:

public java.lang.String ()

In this example, if I replace:

Constructor c = String.class.getConstructor();

by:

Constructor c = String.class.getConstructor((Class<?>[]) null);

I get the same result ...

why and what is subtlety?

Thanks in advance.

+4
source share
4 answers

They do the same thing.

When you call String.class.getConstructor(), you actually have an empty array Class<?>as an argument. This is equivalent to calling with (Class<?>[]) null, which can be seen by checking how it compares the type parameters with the constructors in the constructor:

private static boolean arrayContentsEq(Object[] a1, Object[] a2) {
    if (a1 == null) {
        return a2 == null || a2.length == 0;
    }

    if (a2 == null) {
        return a1.length == 0;
    }

    if (a1.length != a2.length) {
        return false;
    }

    for (int i = 0; i < a1.length; i++) {
        if (a1[i] != a2[i]) {
            return false;
        }
    }

    return true;
}

, . , new Class<?>[0] .

+4

Just read the manual.

public java.lang.reflect.Constructor getConstructor(java.lang.Class[] parameterTypes)

It accepts constructor parameter types. This is necessary in case of constructor overload.

+1
source

if you write

    System.out.println(String.class.getConstructor(String.class));

Output public java.lang.String (java.lang.String)

0
source

All Articles