code.rar
一、Java 反射
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
二、啥时候使用反射
在 Java 程序中许多对象在运行时都会出现两种类型:编译时类型
和 运行时类型
。
编译时的类型由声明对象时使用的类型来决定,运行时类型由实际赋值给对象的类型决定。
如:
而通常在运行时我们是无法获取到运行时类型的具体方法,案例如下
通过上述代码能够知道存在的问题是:无法访问 Student 中的属性!
这时候就需要使用反射!
三、反射相关 API 使用
获取 class 对象
Object.getClass()
比如: Person student = new Student(xxx); Class<? extends Person> aClass = student.getClass();
Object.class
比如:
Class clazz = Student.class;
CLass.forName("class 全类名")
比如:
Class clazz = Class.forName("com.zhixing.Student")
反射越过泛型检查
class Test{
public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
List<String> strArr = new ArrayList<>();
strArr.add("zhixing");
Class<? extends List> clazz = strArr.getClass();
Method addMethod = clazz.getMethod("add", Object.class);
addMethod.invoke(strArr, 100);
//遍历集合
for (Object obj : strArr) {
System.out.println(obj);
}
// java 8 无法遍历 :异常:Integer cannot be cast to String
//strArr.stream().forEach(System.out::println);
}
}