get public Object get(Object obj) throws IllegalArgumentException, IllegalAccessExceptionIf the underlying field is a static field, the obj argument is ignored; it may be null. 其他几种类型都可以直接用f1.getXXX(obj,比如: getBoolean public boolean getBoolean(Object obj) throws IllegalArgumentException, IllegalAccessException Gets the value of a static or instance boolean field.
我是这样用的啊System.out.println(f1.getInt(null));错误是java.lang.IllegalAccessException: Class amytest.TestStatic can not access a member of class Test with modifiers "public static" at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57) at java.lang.reflect.Field.doSecurityCheck(Field.java:811) at java.lang.reflect.Field.getFieldAccessor(Field.java:758) at java.lang.reflect.Field.getInt(Field.java:369) at amytest.TestStatic.main(TestStatic.java:29) Exception in thread "main" 换成getDeclaredField也是一样的错误
import java.lang.reflect.*;public class Test { public static String name = "敏司令";
public void setName(String name) { this.name = name; }
public String getName() { return name; }
public static void main(String[] args) throws Exception { Class clazz = Class.forName("Test"); Field fld = clazz.getField("name"); System.out.println(fld.get(null)); fld.set(null,"司令"); System.out.println(fld.get(null)); } }
public Object get(Object obj)
throws IllegalArgumentException,
IllegalAccessExceptionIf the underlying field is a static field, the obj argument is ignored; it may be null. 其他几种类型都可以直接用f1.getXXX(obj,比如:
getBoolean
public boolean getBoolean(Object obj)
throws IllegalArgumentException,
IllegalAccessException
Gets the value of a static or instance boolean field.
at sun.reflect.Reflection.ensureMemberAccess(Reflection.java:57)
at java.lang.reflect.Field.doSecurityCheck(Field.java:811)
at java.lang.reflect.Field.getFieldAccessor(Field.java:758)
at java.lang.reflect.Field.getInt(Field.java:369)
at amytest.TestStatic.main(TestStatic.java:29)
Exception in thread "main" 换成getDeclaredField也是一样的错误
{
public static String name = "敏司令";
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public static void main(String[] args) throws Exception
{
Class clazz = Class.forName("Test");
Field fld = clazz.getField("name");
System.out.println(fld.get(null));
fld.set(null,"司令");
System.out.println(fld.get(null));
}
}