这里写自定义目录标题
一、什么是Java反射机制
1、什么是反射?
反射允许程序在执行期间借助于反射api获取任何类的内部信息,并能直接操作任意对象的内部属性及方法
2、Java反射机制提供的功能
Java反射能够做什么事情呢?
- 在运行时构造任意一个类的对象
- 在运行时获取一个类所具有的成员变量、构造器、方法
- 在运行时调用任意一个对象的成员变量和方法
- 在运行时获取泛型信息
- 在运行时获取注解信息
3、反射相关的主要 api
见下面
二、理解Class类并获取Class实例
1、什么是Class类
当字节码文件加载到jvm中成为一个运行时类,这个运行时类就是 Class的一个实例
2、获取Class类的实例(四种方法)
// 1、调用类的 .class属性
Class clazz1 = Person.class;
System.out.println(clazz1);
// 2、调用实例的getClass()方法
Person p = new Person();
Class<? extends Person> clazz2 = p.getClass();
System.out.println(clazz2);
System.out.println(clazz1 == clazz2);
// 3、已知一个类的全类名,且该类在类路径下,可通过Class类的静态方法forName()获取,可能抛出ClassNotFoundException
Class<?> clazz3 = Class.forName("high_character15.Person");
System.out.println(clazz3);
// 4、其他
ClassLoader cl = this.getClass().getClassLoader();
Class clazz4 = cl.loadClass("high_character15.Person");
System.out.println(clazz4);
3、哪些类型可以有Class对象?
(1)class:
外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
(2)interface:接口
(3)[]:数组
(4)enum:枚举
(5)annotation:注解@interface
(6)primitive type:基本数据类型
(7)void
三、类的加载和ClassLoader的理解
1、类的加载过程
四、创建运行时类的对象
有了Class对象,能做什么?
创建类的对象:调用Class对象的newInstance()方法
@Test
public void test1() throws IOException, InstantiationException, IllegalAccessException {
Class<Person> clazz1 = Person.class;
Person person = clazz1.newInstance();
System.out.println(person);
}
//体会反射的动态性
@Test
public void test2(){
for(int i = 0;i < 100;i++){
int num = new Random().nextInt(3);//0,1,2
String classPath = "";
switch(num){
case 0:
classPath = "java.util.Date";
break;
case 1:
classPath = "java.lang.Object";
break;
case 2:
classPath = "com.atguigu.java.Person";
break;
}
try {
Object obj = getInstance(classPath);
System.out.println(obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/*
创建一个指定类的对象。
classPath:指定类的全类名
*/
public Object getInstance(String classPath) throws Exception {
Class clazz = Class.forName(classPath);
return clazz.newInstance();
}
五、获取运行时类的完整结构
通过反射获取运行时类的 Field、Method、Constructor、Superclass、Interface、Annotation
1、获取运行时类的属性
- getFields : 获取当前运行时类及其父类中申明为public访问权限的属性
- getDeclaredFields: 获取当前运行时类中申明的所有属性(不包含父类中申明的属性)
- getModifiers : 获取变量的权限修饰符
- getType:获取变量的数据类型
- getName:获取变量名
public void testField() {
Class clazz = Person.class;
// getFields : 获取当前运行时类及其父类中申明为public访问权限的属性
Field[] fields = clazz.getFields();
for (Field field : fields) {
System.out.println(field);
}
// getDeclaredFields: 获取当前运行时类中申明的所有属性(不包含父类中申明的属性)
Field[] fields1 = clazz.getDeclaredFields();
for (Field field : fields1) {
System.out.println(field);
}
for (Field field : fields1) {
// 获取变量的权限修饰符
int modifier = field.getModifiers();
System.out.println(Modifier.toString(modifier));
// 获取变量的数据类型
Class<?> type = field.getType();
System.out.println(type);
// 获取变量名
String fieldName = field.getName();
System.out.println(fieldName);
}
}
2、获取运行时类的方法
- getMethods: 获取当前运行时类及其父类中申明为public的方法
- getDeclaredMethods: 获取当前运行时类中申明的所有方法(不包含父类)
- getAnnotations() : 获取方法上标注的注解
- getModifiers() : 获取方法的修饰符
- getReturnType():获取方法的返回值类型
- getName():获取方法的方法名
- getParameterTypes() : 获取方法的形参列表
public void testMethod() {
Class clazz = Person.class;
//getMethods: 获取当前运行时类及其父类中申明为public的方法
Method[] methods = clazz.getMethods();
for (Method method : methods) {
System.out.println(method);
}
System.out.println();
// getDeclaredMethods: 获取当前运行时类中申明的所有方法(不包含父类)
Method[] methods1 = clazz.getDeclaredMethods();
for (Method method : methods1) {
System.out.println(method);
}
System.out.println();
for (Method method : methods1) {
// 获取方法上标注的注解
Annotation[] annotations = method.getAnnotations();
for (Annotation annotation : annotations) {
System.out.print(annotation + " ");
}
// 获取方法的修饰符
int modifiers = method.getModifiers();
System.out.print(Modifier.toString(modifiers) + " ");
// 获取方法的返回值类型
Class returnType = method.getReturnType();
System.out.print(returnType + " ");
// 获取方法的方法名
String name = method.getName();
System.out.print(name + " ");
// 获取方法的形参列表
Class[] parameterTypes = method.getParameterTypes();
System.out.print("(");
if (parameterTypes != null && parameterTypes.length > 0) {
for (Class parameterType : parameterTypes) {
System.out.print(parameterType + ", ");
}
}
System.out.print(")");
System.out.println();
}
}
3、获取运行时类的构造器
- getConstructors():获取当前运行时类中声明为public的构造器
- getDeclaredConstructors():获取当前运行时类中声明的所有的构造器
public void testConstructure() {
Class clazz = Person.class;
//getConstructors():获取当前运行时类中声明为public的构造器
Constructor[] constructors = clazz.getConstructors();
for(Constructor c : constructors){
System.out.println(c);
}
System.out.println();
//getDeclaredConstructors():获取当前运行时类中声明的所有的构造器
Constructor[] declaredConstructors = clazz.getDeclaredConstructors();
for(Constructor c : declaredConstructors){
System.out.println(c);
}
}
4、获取运行时类的父类
- getSuperclass() : 获取运行时类的父类
- getGenericSuperclass():获取运行时类的带泛型的父类
// 获取运行时类的父类
public void test2(){
Class clazz = Person.class;
Class superclass = clazz.getSuperclass();
System.out.println(superclass);
}
// 获取运行时类的带泛型的父类
public void test3(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
System.out.println(genericSuperclass);
}
获取运行时类的带泛型的父类的泛型
@Test
public void test4(){
Class clazz = Person.class;
Type genericSuperclass = clazz.getGenericSuperclass();
ParameterizedType paramType = (ParameterizedType) genericSuperclass;
//获取泛型类型
Type[] actualTypeArguments = paramType.getActualTypeArguments();
//System.out.println(actualTypeArguments[0].getTypeName());
System.out.println(((Class)actualTypeArguments[0]).getName());
}
5、获取运行时类的泛型
6、获取运行时类的接口
- getInterfaces():获取运行时类实现的接口
- getSuperclass().getInterfaces() :获取运行时类的父类实现的接口
public void test5(){
Class clazz = Person.class;
// 获取运行时类实现的接口
Class[] interfaces = clazz.getInterfaces();
for(Class c : interfaces){
System.out.println(c);
}
System.out.println();
//获取运行时类的父类实现的接口
Class[] interfaces1 = clazz.getSuperclass().getInterfaces();
for(Class c : interfaces1){
System.out.println(c);
}
}
7、获取运行时类所在的包
- getPackage():获取运行时类所在的包
public void test6(){
Class clazz = Person.class;
Package pack = clazz.getPackage();
System.out.println(pack);
}
8、获取运行时类声明的注解
getAnnotations(): 获取运行时类声明的注解
@Test
public void test7(){
Class clazz = Person.class;
Annotation[] annotations = clazz.getAnnotations();
for(Annotation annos : annotations){
System.out.println(annos);
}
}
【小结】
- 并不会经常使用
- 熟悉各种反射api,因为想要看懂框架源码的话,必须掌握 反射和注解
六、调用运行时类的指定结构
1、调用指定方法
public void testMethod() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
/*
1.获取指定的某个方法
getDeclaredMethod():参数1 :指明获取的方法的名称 参数2:指明获取的方法的形参列表
*/
Method show = clazz.getDeclaredMethod("show", String.class);
//2.保证当前方法是可访问的
show.setAccessible(true);
/*
3. 调用方法的invoke():参数1:方法的调用者 参数2:给方法形参赋值的实参
invoke()的返回值即为对应类中调用的方法的返回值。
*/
Object returnValue = show.invoke(p,"CHN"); //String nation = p.show("CHN");
System.out.println(returnValue);
System.out.println("*************如何调用静态方法*****************");
Method showDesc = clazz.getDeclaredMethod("showDesc");
showDesc.setAccessible(true);
//如果调用的运行时类中的方法没有返回值,则此invoke()返回null
Object returnVal = showDesc.invoke(Person.class);
System.out.println(returnVal);//null
}
2、调用指定属性
public void testField1() throws Exception {
Class clazz = Person.class;
//创建运行时类的对象
Person p = (Person) clazz.newInstance();
//1. getDeclaredField(String fieldName):获取运行时类中指定变量名的属性
Field name = clazz.getDeclaredField("name");
//2.保证当前属性是可访问的
name.setAccessible(true);
//3.获取、设置指定对象的此属性值
name.set(p,"Tom");
System.out.println(name.get(p));
}
3、调用构造器
public void testConstructor() throws Exception {
Class clazz = Person.class;
//private Person(String name)
/*
1.获取指定的构造器
getDeclaredConstructor():参数:指明构造器的参数列表
*/
Constructor constructor = clazz.getDeclaredConstructor(String.class);
//2.保证此构造器是可访问的
constructor.setAccessible(true);
//3.调用此构造器创建运行时类的对象
Person per = (Person) constructor.newInstance("Tom");
System.out.println(per);
}
7、反射的应用:动态代理
interface Human{
String getBelief();
void eat(String food);
}
//被代理类
class SuperMan implements Human{
@Override
public String getBelief() {
return "I believe I can fly!";
}
@Override
public void eat(String food) {
System.out.println("我喜欢吃" + food);
}
}
/*
要想实现动态代理,需要解决的问题?
问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象。
问题二:当通过代理类的对象调用方法a时,如何动态的去调用被代理类中的同名方法a。
*/
class ProxyFactory{
//调用此方法,返回一个代理类的对象。解决问题一
public static Object getProxyInstance(Object obj){//obj:被代理类的对象
MyInvocationHandler handler = new MyInvocationHandler();
handler.bind(obj);
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),handler);
}
}
class MyInvocationHandler implements InvocationHandler{
private Object obj;//需要使用被代理类的对象进行赋值
public void bind(Object obj){
this.obj = obj;
}
//当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
//将被代理类要执行的方法a的功能就声明在invoke()中
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
//obj:被代理类的对象
Object returnValue = method.invoke(obj,args);
//上述方法的返回值就作为当前类中的invoke()的返回值。
return returnValue;
}
}
public class ProxyTest {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
//proxyInstance:代理类的对象
Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
//当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法
String belief = proxyInstance.getBelief();
System.out.println(belief);
}
}