Java 反射
优点:
(1)能够运行时动态获取类的实例,大大提高系统的灵活性和扩展性。
(2)与Java动态编译相结合,可以实现强大的功能
缺点:
(1)使用反射的性能较低
(2)使用反射相对来说不安全
(3)破坏了类的封装性,可以通过反射获取这个类的私有方法和属性
方法:
Class.forName("oiios.com.Test"):获取oiios.com包下Test的类对象
newInstance:通过类对象生成对应的实例对象
getMethods:获得public修饰的方法
getDeclaredMethods:获得非public修饰的方法
getFields:获得public修饰的属性
getDeclaredFields:获取非public修饰的属性
setAccessible:是否抑制Java的访问控制检查,若设置为false,则会出现IllegalAccessException异常(can notaccess a member of with modifiers "private")
下面通过一个例子简单介绍反射:
package oiios.com;
public class Test {
private int a=5;
private String test(boolean flag) {
if (flag) {
return "true";
}else {
return "false";
}
}
}
调用上面private修饰的方法及属性:
package oiios.com;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionDemo {
public static void main(String[] args) {
try {
//通过包名+类名获得对应的类对象
Class<?> c = Class.forName("oiios.com.Test");
//生成对象的实例
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("test", boolean.class);
method.setAccessible(true);// 抑制Java的访问控制检查
Object obj1 = method.invoke(obj, new Object[] {true});
System.out.println(obj1);
//获取属性名
Field field = c.getDeclaredField("a");
// 抑制Java的访问控制检查,不加会出现IllegalAccessException异常(can not access a member of with modifiers "private")
field.setAccessible(true);
System.out.println(field.get(obj));
//返回public修饰的方法
// Method[] method = c.getMethods();
//返回非public修饰的方法
// Method[] method = c.getDeclaredMethods();
// for (Method method2 : method) {
// System.out.println(method2.getName());
// }
} catch (Exception e) {
e.printStackTrace();
}
}
}