public class Clazz1 { public int test = 10; public enum test {a, s, d, f }; public static void main() { System.out.println("a: " + Clazz1.test.a); } }
When is this done
$ javac Clazz1.java Clazz1.java:8: error: non-static variable test cannot be referenced from a static context System.out.println("a: " + Clazz1.test.a); ^ Clazz1.java:8: error: int cannot be dereferenced System.out.println("a: " + Clazz1.test.a); ^
Enumerations are actually special types of classes, and using the enum keyword causes the class to be created. For instance:
import java.util.Arrays; import static java.lang.System.out; public class Clazz1 { public enum test { a, b, c, d, e, f; }; public static int test = 10; public static void main(String[] args) { Class<?> ec = Clazz1.test.class; out.format("Name: %s, constants: %s%n\n", ec.getName(), Arrays.asList(ec.getEnumConstants())); } }
Now you can use the ec and Enum class methods to get objects. The fact is that you REALLY do not want to do this. Because it is equivalent:
class Foo { class Bar { } int Bar; }
What will make javak spit unnecessary epitaphs.
For more information on Enum reflection classes, check out the java api documentation
source share