Michael B Michael B - 15 days ago 9
Java Question

How to properly specify a Class<?> parameter using Generics

My goal is to implement an operation that accepts class instances, but only if the concrete passed class inherits from Collection.

I get compiler warnings on my code that I cannot resolve.

package com.fun.with.generics;

import java.util.ArrayList;
import java.util.Collection;

public class AcceptTypedClass
{
// Warning here on 'Collection': ... raw type, references should be parameterized.
private static void printCollectionClass( Class<? extends Collection> c )
{
System.out.println( c.getName() );
}

public static void main( String[] args )
{
// Warning here on ArrayList: ... raw type, references should be parameterized.
Class<ArrayList> arrayList = ArrayList.class;
printCollectionClass( arrayList );
}
}


I do understand the warning message, but if I fix the warning by adding the missing type arguments like shown below, I get an error.

Class<ArrayList<?>> arrayList = ArrayList.class;


Can somebody explain this? The question is if I can write the above code so that I get no warning (and the code works)?

Answer

You can change printCollectionClass method to

private static <T extends Collection<?>> void printCollectionClass(Class<T> c) {
        System.out.println(c.getName());
    }
public static void main(String[] args) {
        printCollectionClass(ArrayList.class);
    }

Here printCollectionClass will accept class which inherit from collection.