Search code examples
javaparameterized-types

Is the return Object of getConstructors() method not array of parameterized type?


in this Link, it is declared that we can not create an array of parameterzide type. Create an Array of Arraylists

but in java reflect, we can call getConstructors() method and save it's returned objects as below.

Constructor<?>[] constructors = MyClass.class.getConstructors();

so the question is, isn't it also a parameterized type object ?

Constructor<?>[]

if yes, then why does it work here ?


Solution

  • Good question. You can surely define an array of parameterized type bye breaking type safety like,

    ArrayList<Individual> [] group = new ArrayList()[4] //unchecked warning
    

    Arrays are covariant subtypes, which means Strings [] is a subtype of Object [] and are implemented in way that the elements we are adding is checked at runtime for there types like,

    String [] stArr = new String[10]
    Object [] objects = strings;
    objects[0] = new Integer(); // Runtime ArrayStoreException will be thrown
    

    To prevent wrong assignments, compiler does runtime checks of every array assignment.

    while generics are compile time only. So Java would not be able to identify generic type once aliased to subtype, like,

    ArrayList<Integer> [] lstArr = new ArrayList[10];
    Object [] objArr= lstArr;
    ArrayList<String> strList = new ArrayList<String>();        
    objArr[0] = strList; // No runtime exception here
    

    Unbounded wildcard type is only way as while putting the elements, no real type check is required for unbounded wildcard type.

    ArrayList<?>[] lstArr = new ArrayList<?>[10];
    lstArr[0] = new ArrayList<Integer>();
    

    Hope this answers your question.