Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Class<?>

I came across this code:

public class RestfulAdage extends Application {
  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> set = new HashSet<Class<?>>();
    set.add(Adages.class);
    return set;
  }
}

I do not understand what Class<?> means.

like image 614
user3134565 Avatar asked Feb 14 '14 12:02

user3134565


2 Answers

Class<?> refers to a class of unknown type. The notation uses an unbounded generic which places no restriction on the type of class that can be added to the Collection. For example the following would not work

Set<Class<String>> set = new HashSet<Class<String>>();
set.add(Adages.class); // type not allowed
like image 162
Reimeus Avatar answered Nov 15 '22 23:11

Reimeus


Class is a parametrizable class, hence you can use the syntax Class where T is a type. By writing Class, you're declaring a Class object which can be of any type (? is a wildcard). The Class type is a type that contains metainformation about a class.

It's always good practice to refer to a generic type by specifying his specific type, by using Class you're respecting this practice (you're aware of Class to be parametrizable) but you're not restricting your parameter to have a specific type.

Reference about Generics and Wildcards: http://docs.oracle.com/javase/tutorial/java/generics/wildcards.html

Reference about Class object and reflection the (feature of Java language used to introspect itself): http://java.sun.com/developer/technicalArticles/ALT/Reflection/

like image 36
Yogesh Lakhotia Avatar answered Nov 16 '22 00:11

Yogesh Lakhotia