--
Java Reflection provides three enum-specific APIs:
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
package com.abcd; import java.lang.reflect.Field; import java.util.Arrays; import static java.lang.System.out; enum Color { WHITE, BLACK, RED, YELLOW, BLUE; } public class Program { private Color color = Color.RED; public static void main(String... args) { Class c = Color.class; if (c.isEnum()) { out.format("Enum name: %s%nEnum constants: %s%n", c.getName(), Arrays.asList(c.getEnumConstants())); } try { Program obj = new Program(); Field f = obj.getClass().getDeclaredField("color"); f.setAccessible(true); Color clr = (Color)f.get(obj); out.format("Original Color : %s%n", clr); f.set(obj, Color.BLUE); out.format(" New Color : %s%n", f.get(obj)); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { e.printStackTrace(); } } } /* Enum name: com.abcd.Color Enum constants: [WHITE, BLACK, RED, YELLOW, BLUE] Original Color : RED New Color : BLUE */
Comments
Post a Comment