enum的值在编译过后设计static和final。我想利用反射来修改请问可以吗??
[b]但是单独的static 或者final的,都是可以修改的。[/b]
[b]
不可以,测试如下:[/b]
[code="java"]
package ceshi;
import java.lang.reflect.Field;
public class EnumTest {
public final static MyEnum test = MyEnum.RED;
public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
Class clazz = EnumTest.class;
Field field = clazz.getDeclaredField("test");
field.setAccessible(true);
field.set(null, MyEnum.GREEN);
System.out.println(field.get(null));
}
}
enum MyEnum{
RED,GREEN
}[/code]
[b]
输出:[/b]
[color=red]Exception in thread "main" java.lang.IllegalAccessException: Can not set static final ceshi.MyEnum field ceshi.EnumTest.test to ceshi.MyEnum[/color]