2012年7月20日
- java.lang.IllegalAccessException:
- Class com.test.accessible.Main
- can not access
- a member of class com.test.accessible.AccessibleTest
- with modifiers "private"
java代码中,常常将一个类的成员变量置为private 在类的外面获取此类的私有成员变量的value时,需要注意: 测试类:
public class AccessibleTest {
private int id;
private String name;
public AccessibleTest() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Main类:
public class Main {
public static void main(String[] args) throws Exception {
Class clazz = Class.forName("com.test.accessible.AccessibleTest");
AccessibleTest at = new AccessibleTest();
at.setId(1);
at.setName("AT");
for (Field f : clazz.getDeclaredFields()) {
f.setAccessible(true);//AccessibleTest类中的成员变量为private,故必须进行此操作
System.out.println(f.get(at));//获取当前对象中当前Field的value
}
}
}
如果没有在获取private的Field之前调用setAccessible(true)方法,异常:
java.lang.IllegalAccessException:
Class com.test.accessible.Main
can not access
a member of class com.test.accessible.AccessibleTest
with modifiers "private"
当然在AccessibleTest类的内部(AccessibleTest的内部类除外)
进行如上操作则不需要调用setAccesible()方法
**另外:由于Accessible的
值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。
值为 false 则指示反射的对象应该实施 Java 语言访问检查。 将其设为true,可以
提高java反射速度
posted @
2012-07-20 13:51 dping 阅读(647) |
评论 (0) |
编辑 收藏
转自:
http://technet.microsoft.com/zh-cn/library/aa989722 功能:
Gets the field (public, private, or protected) with the given name. 原型:
public java.lang.reflect.Field getDeclaredField(java.lang.String fieldName)Example:
// class_getdeclaredfield.jsl
import java.lang.reflect.Field;
import java.util.Date;
public class Program
{
public static void main(String[] args)
{
try
{
// Get the Class object associated with this class.
Program program = new Program();
Class progClass = program.getClass();
// Get the field named str.
Field strField = progClass.getDeclaredField("str");
System.out.println("Field found: " + strField.toString());
// Get the field named date.
Field dateField = progClass.getDeclaredField("date");
System.out.println("Field found: " + dateField.toString());
// Get the field named i.
Field iField = progClass.getDeclaredField("i");
System.out.println("Field found: " + iField.toString());
}
catch (NoSuchFieldException ex)
{
System.out.println(ex.toString());
}
}
public Program()
{
}
public Program(String str, Date date, int i)
{
this.str = str;
this.date = date;
this.i = i;
}
public String str = "Hello";
private Date date = new Date();
protected int i = 0;
}
/*
Output:
Field found: public java.lang.String Program.str
Field found: private java.util.Date Program.date
Field found: protected int Program.i
*/
注:
getFields()获得某个类的所有的公共(public)的字段,包括父类。
getDeclaredFields()获得某个类的所有申明的字段,即包括public、private和proteced,但是不包括父类的申明字段。
posted @
2012-07-20 13:01 dping 阅读(582) |
评论 (0) |
编辑 收藏