How to Use Reflection to Access Fields with Enum Types of a Class in Java?
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
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
*/
Most Recent java Faqs
- How to uncompress a file in the gzip format?
- How to make a gzip file in Java?
- How to use Java String.split method to split a string by dot?
- How to validate URL in Java?
- How to schedule a job in Java?
- How to return the content in the correct encoding from a servlet?
- What is the difference between JDK and JRE?
Most Viewed java Faqs
- How to read input from console (keyboard) in Java?
- How to use HttpURLConnection POST data to web server?
- How to add BASIC Authentication into HttpURLConnection?
- How to Retrieve Multiple Result Sets from a Stored Procedure in JDBC?
- What are class variables in Java?
- What are local variables in Java?
- How to Use Updatable ResultSet in JDBC?