您的位置:首页 > 编程语言 > Java开发

Java反射

2016-03-01 10:16 495 查看
一、对于任意一个类,都能知道这个类的所有属性和方法,对于任意一个对象,都能调用他的任意一个方法

二、获取反射机制的三种方法

1、Class c1 = Class.forName(“Employee”)

2、Class c2 = Employee.class;

3、Employee e = new Employee();

Class c3 = e.getClass();

创建对象:

Object o = c1.newInstance();

三、获取属性及方法

1、获取所有属性

Class c = ViewConfiguration.class;
Field[] fs = c.getDeclaredFields();
StringBuffer sb = new StringBuffer();
sb.append(Modifier.toString(c.getModifiers()) + "class" + c.getSimpleName());//获取类的修饰符private public protected
for(Field field:fs){
sb.append(Modifier.toString(field.getModifiers())+" ");//获取属性的修饰符
sb.append(field.getType().getSimpleName()+" ");//获取属性的类型
sb.append(field.getName());//获取属性的名字
}


2、获取特定名字的属性

ViewConfiguration configuration = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
//打破封装
menuKeyField.setAccessible(true);
//给属性赋值
menuKeyField.setBoolean(configuration, false);


3、获取方法

try {
Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible",Boolean.TYPE);
m.setAccessible(true);
m.invoke(menu,true);
} catch (Exception e) {
e.printStackTrace();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: