Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Same names of enum and variable

Tags:

java

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?

like image 343
mmatloka Avatar asked Oct 23 '11 20:10

mmatloka


2 Answers

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

like image 88
Ahmed Masud Avatar answered Nov 03 '22 14:11

Ahmed Masud


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:

  • Enum names (as other class and interface names) should be in UpperCamelCase
  • local variable names and field names should be in lowerCamelCase
  • constants (static and final fields) should be in UPPER_UNDERSCORE_CASE.
like image 37
Sean Patrick Floyd Avatar answered Nov 03 '22 14:11

Sean Patrick Floyd