FAQ

Java

JSP

Servlet


Advertisement



How to Use Reflection to Access Fields with Enum Types of a Class in Java?

Java Reflection provides three enum-specific APIs:

The following example shows how to get and set fields with Java Enum Types:

package com.xyzws;

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.xyzws.Color
Enum constants: [WHITE, BLACK, RED, YELLOW, BLUE]
Original Color : RED
New Color : BLUE
*/


Printer-friendly version Printer-friendly version | Send this 
article to a friend Mail this to a friend

Previous Next vertical dots separating previous/next from contents/index/pdf Contents

  |   |