Java反射

1.Java反射机制

  JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射机制。JAVA反射(放射)机制:“程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言”。Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods。

2.利用Java反射能够实现的功能

  Java反射机制主要提供了以下功能:

  •   在运行时判断任意一个对象所属的类;
  •   在运行时构造任意一个类的对象;
  •   在运行时判断任意一个类所具有的成员变量和方法;
  •   在运行时调用任意一个对象的方法;
  •   生成动态代理。

3.关于反射机制的API

A.实例化Class类对象

 1 package com.rong.se;
 2 public class MyReflect {
 3     public static void main(String[] args) {
 4         try {
 5             //最常用的一种方式! 一般采用这种形式!
 6             Class<?> class1 = Class.forName("com.rong.se.MyReflect");
 7             Class<MyReflect> class2=MyReflect.class;
 8             Class<? extends MyReflect> class3 = new MyReflect().getClass();
 9             
10             System.out.println(class1.getName());
11             System.out.println(class2.getName());
12             System.out.println(class3.getName());
13         } catch (Exception e) {
14             e.printStackTrace();
15         }
16     }
17 }

B,获取一个对象的父类与实现的接口

 1 package com.rong.se;
 2 import java.io.Serializable;
 3 public class MyReflect implements MyInterface,Serializable{
 4     private static final long serialVersionUID = -573708754998864848L;
 5 
 6     public static void main(String[] args) {
 7         try {
 8             Class<?> myClass=Class.forName("com.rong.se.MyReflect");
 9             //获取父类Class
10             Class<?> superclass = myClass.getSuperclass();
11             //打印父类的完整类名(java.lang.Object)
12             System.out.println(superclass.getName());
13             // 获取所有的接口
14             Class<?>[] interfaces = myClass.getInterfaces();
15             for (Class<?> class1 : interfaces) {
16                 System.out.println(class1.getSimpleName());
17                 System.out.println(class1.getName());
18                 System.out.println(class1.getPackage());
19             }
20             
21         } catch (Exception e) {
22             e.printStackTrace();
23         }
24     }
25 }

C.获取某个类中的全部构造函数—通过反射机制实例化一个类的对象

 1 package com.rong.se;
 2 import java.io.Serializable;
 3 import java.lang.reflect.Constructor;
 4 public class MyReflect implements MyInterface,Serializable{
 5     private static final long serialVersionUID = -573708754998864848L;
 6 
 7     public static void main(String[] args) {
 8         try {
 9             Class<?> myClass=Class.forName("com.rong.se.Student");
10             //使用Student类的默认无参构造方法创建对象
11             Student student = (Student)myClass.newInstance();
12             student.setAge(20);
13             student.setName("胡歌");
14             student.setPwd("5201314");
15             System.out.println(student);
16             //取出所有的构造方法
17             Constructor<?>[] constructors = myClass.getConstructors();
18             //查看每个构造方法的参数类型
19             for (Constructor<?> constructor : constructors) {
20                 Class<?>[] parameterTypes = constructor.getParameterTypes();
21                 for (Class<?> class1 : parameterTypes) {
22                     //System.out.println(class1.getTypeName());
23                     System.out.println(class1.getName());
24                 }
25                 System.out.println("################");
26             }
27             //使用构造方法创建对象
28             Student stu0 = (Student) constructors[1].newInstance("yyyy","mima",37);
29             System.out.println(stu0);
30             Student stu = (Student) constructors[2].newInstance("容杰龙","woshirjl");
31             System.out.println(stu);
32         } catch (Exception e) {
33             e.printStackTrace();
34         }
35     }
36 }
package com.rong.se;

public class Student implements Serializable,MyInterface{
    public Student(String name, String pwd) {
        super();
        this.name = name;
        this.pwd = pwd;
    }

    public Student(String name, String pwd, Integer age) {
        super();
        this.name = name;
        this.pwd = pwd;
        this.age = age;
    }
    
    public Student() {
        super();
    }
    
    private String name;
    private String pwd;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [name=" + name + ", pwd=" + pwd + ", age=" + age + "]";
    }

}

D.获取某个类的全部属性

package com.rong.se;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
public class MyReflect implements MyInterface,Serializable{
    private static final long serialVersionUID = -573708754998864848L;
    public static void main(String[] args) {
        try {
            Class<?> myClass=Class.forName("com.rong.se.Student");
            //获取Student类内部声明的属性
            Field[] declaredFields = myClass.getDeclaredFields();
            for (Field field : declaredFields) {
                
                //属性修饰符
                int modifiers = field.getModifiers();
                String  modifiersName= Modifier.toString(modifiers);
                //属性类型
                Class<?> type = field.getType();
                String typeName = type.getName();
                //属性名
                String fieldName = field.getName();
                System.out.println(modifiersName+" "+typeName+" "+fieldName);
                
            }
            System.out.println("#########################################");
            //获取Student类实现的接口或者继承的父类的属性
            Field[] fields = myClass.getFields();
            for (Field field : fields) {
                //属性修饰符
                int modifiers = field.getModifiers();
                String modifiersName = Modifier.toString(modifiers);
                //属性类型
                Class<?> type = field.getType();
                String typeName = type.getName();
                //属性名
                String fieldName = field.getName();
                System.out.println(modifiersName+" "+typeName+" "+fieldName);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

E.获取某个类的全部方法

 1 package com.rong.se;
 2 import java.io.Serializable;
 3 import java.lang.reflect.Field;
 4 import java.lang.reflect.Method;
 5 import java.lang.reflect.Modifier;
 6 public class MyReflect implements MyInterface,Serializable{
 7     private static final long serialVersionUID = -573708754998864848L;
 8     public static void main(String[] args) throws ClassNotFoundException {
 9             Class<?> myClass=Class.forName("com.rong.se.MyReflect");
10             //获取所有方法(包括继承父类以及实现接口的方法)
11             Method[] methods = myClass.getMethods();
12             for (Method method : methods) {
13                 System.out.println(method);
14                 //方法修饰符
15                 int modifiers = method.getModifiers();
16                 String modifiersName = Modifier.toString(modifiers);
17                 //方法返回值类型
18                 Class<?> returnType = method.getReturnType();
19                 String returnTypeName = returnType.getName();
20                 //方法名
21                 String methodName = method.getName();
22                 System.out.println(modifiersName+" "+returnTypeName+" "+methodName);
23                 //方法参数类型
24                 Class<?>[] parameterTypes = method.getParameterTypes();
25                 for (Class<?> parameter : parameterTypes) {
26                     System.out.println(parameter.getName());
27                 }
28                 //方法向上抛出的异常
29                 Class<?>[] exceptionTypes = method.getExceptionTypes();
30                 for (Class<?> exception : exceptionTypes) {
31                     System.out.println(exception.getName());
32                 }
33                 System.out.println("=================================");
34             }
35     }
36 }

F.通过反射机制调用某个类的方法

package com.rong.se;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class MyReflect implements MyInterface, Serializable {
    private static final long serialVersionUID = -573708754998864848L;

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
        Class<?> myClass = Class.forName("com.rong.se.MyReflect");
        Object object = myClass.newInstance();
        //调用方法action1
        Method method = myClass.getMethod("action1", null);
        method.invoke(object, null);
        //调用方法action2
        Method method2 = myClass.getMethod("action2", String.class,int.class);
        method2.invoke(object, "rjl",57);
    }

    public void action1() {
        System.out.println("action1调用!");
    }

    public void action2(String name,int age) {
        System.out.println(name+":"+age);
    }
}

G.通过反射机制操作某个类的属性

 1 package com.rong.se;
 2 
 3 import java.io.Serializable;
 4 import java.lang.reflect.Field;
 5 
 6 public class MyReflect implements MyInterface, Serializable {
 7     private static final long serialVersionUID = -573708754998864848L;
 8 
 9     private int age=18;
10     public static void main(String[] args) throws Exception{
11         Class<?> myClass = Class.forName("com.rong.se.MyReflect");
12         Object object = myClass.newInstance();
13         //获取本类声明的属性
14         Field declaredField = myClass.getDeclaredField("age");
15         //设置权限修改为可访问
16         declaredField.setAccessible(true);
17         //修改属性值
18         declaredField.set(object, 20);
19         //获取修改后的属性值
20         System.out.println(declaredField.get(object));
21     }
22 }

H.反射机制的动态代理

  暂时省略。。。。。。

I.反射的应用

在泛型为Integer的ArrayList中存放一个String类型的对象:

package com.rong.se;

import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class MyReflect implements MyInterface, Serializable {
    private static final long serialVersionUID = -573708754998864848L;

    public static void main(String[] args) throws Exception {
        List<Integer> list = new ArrayList<Integer>();
        list.add(123);
        // list.add("hhh");直接添加会出现编译错误
        Class<? extends List> class1 = list.getClass();
        Method method = class1.getMethod("add", Object.class);
        method.invoke(list, "hhh");
        System.out.println(list);
        list.add(57);
        System.out.println(list);
    }
}

原文地址:https://www.cnblogs.com/57rongjielong/p/8027515.html