什么反射?
指Java在运行时动态获取Class类里的注解,属性,方法,构造器,接口,父类等所有信息。
反射的作用?
可以在java运行时动态创建对象,调用方法等。底层是由native实现。
如何使用?
1.Class c1 = Class.forName("classname");
2.Class c1 = Class.getClass();
3.Class c1 = int.class;
动态执行方法
不带Declared用于获取public
动态创建 对象实例 c1.newInstance
Method method=c1.getDeclaredMethod("方法名",匹配参数类型:int.class(无参数为null));
method.invoke("对象实例")
所有属性
for (Field field : c1.getDeclaredFields()) {
System.out.println(field.getName());
}
注解
for (Annotation annotation : c1.getDeclaredAnnotations()) {
System.out.println(annotation);
}
构造器
for (Constructor constructor : c1.getDeclaredConstructors()) {
System.out.println(constructor);
}