I've got following code (I know its not nice ;) ):
public class Clazz1 {
public int test = 10;
public enum test {a, s, d, f }
void sth() {
// ...
}
}
Is there any way to acces this enum? When I type 'test' it always means that int variable. What are rules connected with this situation - why even compiler allows to have enum and int with the same names?
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 this is run
$ 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 class types and the use of enum keyword causes 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()));
}
}
You can now use ec and Enum class methods to get the entities. The thing is that you REALLY don't want to do this. Because it's equivalent of:
class Foo {
class Bar { }
int Bar;
}
Which will make javac spit unneeded epitaphs.
For more information on Enum reflection classes check java api documentation
Accessing static members of the test
enum should still work, and the enum constants are static members. Try Clazz1.test.a
.
Update: no, it doesn't work (see comments), so you'll need to resort to dirty tricks like this:
// this works but is awful not compile-time-safe
test a = Clazz1.test.class.getEnumConstants()[0];
But there are reasons why the Java variable naming conventions exist: to make situations like this less likely, and Java code more readable:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With