Tuesday 29 October 2013

Examining Enums types and example for java


Reflection provides three enum-specific APIs:
Class.isEnum()
Indicates whether this class represents an enum type
Class.getEnumConstants()
Retrieves the list of enum constants defined by the enum in the order they're declared
java.lang.reflect.Field.isEnumConstant()
Indicates whether this field represents an element of an enumerated type
Sometimes it is necessary to dynamically retrieve the list of enum constants; in non-reflective code this is accomplished by invoking the implicitly declared static method values() on the enum. If an instance of an enum type is not available the only way to get a list of the possible values is to invoke Class.getEnumConstants() since it is impossible to instantiate an enum type.
Given a fully qualified name, the EnumConstants example shows how to retrieve an ordered list of constants in an enum usingClass.getEnumConstants().
import java.util.Arrays;
import static java.lang.System.out;

enum Eon { HADEAN, ARCHAEAN, PROTEROZOIC, PHANEROZOIC }

public class EnumConstants {
    public static void main(String... args) {
 try {
     Class<?> c = (args.length == 0 ? Eon.class : Class.forName(args[0]));
     out.format("Enum name:  %s%nEnum constants:  %s%n",
         c.getName(), Arrays.asList(c.getEnumConstants()));
     if (c == Eon.class)
  out.format("  Eon.values():  %s%n",
      Arrays.asList(Eon.values()));

        // production code should handle this exception more gracefully
 } catch (ClassNotFoundException x) {
     x.printStackTrace();
 }
    }
}
Samples of the output follows. User input is in italics.
$ java EnumConstants java.lang.annotation.RetentionPolicy
Enum name:  java.lang.annotation.RetentionPolicy
Enum constants:  [SOURCE, CLASS, RUNTIME]
$ java EnumConstants java.util.concurrent.TimeUnit
Enum name:  java.util.concurrent.TimeUnit
Enum constants:  [NANOSECONDS, MICROSECONDS, 
                  MILLISECONDS, SECONDS, 
                  MINUTES, HOURS, DAYS]
This example also shows that value returned by Class.getEnumConstants() is identical to the value returned by invoking values()on an enum type.
$ java EnumConstants
Enum name:  Eon
Enum constants:  [HADEAN, ARCHAEAN, 
                  PROTEROZOIC, PHANEROZOIC]
Eon.values():  [HADEAN, ARCHAEAN, 
                PROTEROZOIC, PHANEROZOIC] 
 
For Interface Please Go to unit 2;
 

No comments:

Post a Comment