Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a variable which can contain only enum classes?

Tags:

java

I tried this:

public static enum Types { A, B, C }
Class<Enum> e = Types.class;

But I get an "incompatible types" error:

found   : java.lang.Class<id.Types>
required: java.lang.Class<java.lang.Enum>
    Class<Enum> e = Types.class;

As far as I know all enums inherit from Enum. Why is my enum incompatible to Enum?

like image 798
ceving Avatar asked Jul 19 '13 13:07

ceving


1 Answers

Why not just Class<? extends Enum> e = Types.class;?

UPD: I'll give you more explained answer, why your code does not work.

First of all, the type of expression Types.class is Class<Types>, and your variable e is Class<Enum>.

According to JLS 5.5.1 such types (i.e. Class<Types> and Class<Enum>) are provably distinct types (JLS 4.5), and their erasures are same (just Class), so in this case it is compile-time error when you try to cast from Class<Types> to Class<Enum>.

like image 67
Andremoniy Avatar answered Sep 27 '22 23:09

Andremoniy