1

The following code returns an error, but I am not sure why. What needs to be changed to allow for compilation?

switch (DAO.class) {
    case BookDAO.class: 
        return bookDAO;
}
Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
osh
  • 1,191
  • 4
  • 13
  • 21

4 Answers4

16

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (and String from Java 7 onwards). NOT Class types.

DAO.class returns Class object of DAO

Refer this for what .class means

Community
  • 1
  • 1
kosa
  • 65,990
  • 13
  • 130
  • 167
4

From Java Docs

A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer

More On this

stinepike
  • 54,068
  • 14
  • 92
  • 112
Nargis
  • 4,687
  • 1
  • 28
  • 45
3

If you are using Java 7 - you can use switch statements with Strings. Then you could do something like this:

switch (DAO.class.getName()){
    case BookDAO.class.getName() : return bookDAO;
}

getName():

Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

tophernuts
  • 389
  • 9
  • 14
2

Here is the definition of the switch statement:

Unlike if-then and if-then-else statements, the switch statement can have a number of possible execution paths. A switch works with the byte, short, char, and int primitive data types. It also works with enumerated types (discussed in Enum Types), the String class, and a few special classes that wrap certain primitive types: Character, Byte, Short, and Integer (discussed in Numbers and Strings).


So it is not allowed Class type in the switch statement (Class classOfA = A.class;)

Esteban
  • 162
  • 8