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;
}
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;
}
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
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
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;
}
Returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.
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;)