Home > Java > javaTutorial > body text

What is the concept of java reflection mechanism and how to use it

PHPz
Release: 2023-04-18 19:58:26
forward
1208 people have browsed it

What is the concept of java reflection mechanism and how to use it

1. Overview of Java reflection mechanism

1. Java Reflection

(1) Reflection (reflection) is considered a dynamic language The key is that the reflection mechanism allows the program to obtain the internal information of any class with the help of ReflectionAPI during execution, and can directly operate the internal properties and methods of any object.

(2) After loading the class, a Class type object is generated in the method area of ​​the heap memory (a class has only one Class object). This object contains the complete Structural information of the class. We can see the structure of the class through this object. This object is like a mirror, through which we can see the structure of the class, so we vividly call it reflection.
What is the concept of java reflection mechanism and how to use it

2. Dynamic language vs static language

(1) Dynamic language

is a type of language that can change its structure at runtime: for example, new functions, objects, and even codes can be introduced, existing functions can be deleted or other structural changes can be made. In layman's terms, the code can change its structure according to certain conditions at runtime.

Main dynamic languages: Objective-C, C#, JavaScript, PHP, Python, Erlang.

(2) Static language

Corresponding to dynamic language, a language whose runtime structure is immutable is a static language. Such as Java, C, C. Java is not a dynamic language, but Java can be called a "quasi-dynamic language". That is to say, Java has a certain degree of dynamics, and we can use reflection mechanisms and bytecode operations to obtain characteristics similar to dynamic languages. The dynamic nature of Java makes programming more flexible!

(3) Research and application of Java reflection mechanism

Functions provided by Java reflection mechanism

  1. Judge the class to which any object belongs at runtime

  2. Construct an object of any class at runtime

  3. Judge any class at runtime The member variables and methods of the class

  4. Get generic information at runtime and call the member variables and methods of any object at runtime

  5. Process annotations to generate dynamic agents at runtime

Main APIs related to reflection

  1. java.lang.Class: Represents a class

  2. java.lang.reflect.Method:Represents the method of the class

  3. java.lang.reflect.Field:Represents the method of the class Member variable

  4. java.lang.reflect.Constructor: Represents the constructor of the class  …

2. Class class Understanding

1. Class loading process

1.1 Preliminary understanding

After the program passes the javac.exe command, one or more bytecode files (ending with .class).
Then we use the java.exe command to interpret and run a certain bytecode file. Equivalent to loading a certain bytecode file into memory. This process is called class loading. The class loaded into the memory is called a runtime class, and this runtime class serves as an instance of Class.

In other words, an instance of Class corresponds to a runtime class.

The runtime classes loaded into memory will be cached for a certain period of time. Within this time, we can obtain this runtime class in different ways.

1.2 Illustration of the class loading process

When the program actively uses a class, if the class has not been loaded into the memory, the system will pass the following three steps: steps to initialize this class.

What is the concept of java reflection mechanism and how to use it

Class loading: Load the class file bytecode content into memory, and convert these static data into The runtime data structure of the method area, and then generates a java.lang.Class object representing this class, which serves as the access entry (i.e. reference address) to the class data in the method area. All class data that needs to be accessed and used can only be accessed through this Class object. This loading process requires the participation of the class loader.

Class linking: The process of merging the binary code of a Java class into the running state of the JVM.
● Verification: Ensure that the loaded class information complies with JVM specifications, for example: starting with cafe, there are no security issues
● Preparation: formally allocate memory for class variables (static) and set the class In the stage of variable default initial value, these memories will be allocated in the method area.
● Resolution: The process of replacing symbolic references (constant names) in the virtual machine constant pool with direct references (addresses).

类的初始化:
● 执行类构造器【clinit】()方法的过程。类构造器【clinit】()方法是由编译期自动收集类中 所有类变量的赋值动作和静态代码块中的语句合并产生的。(类构造器是构造类信 息的,不是构造该类对象的构造器)。
● 当初始化一个类的时候,如果发现其父类还没有进行初始化,则需要先触发其父类 的初始化。
● 虚拟机会保证一个类的()方法在多线程环境中被正确加锁和同步。

public class ClassLoadingTest {
public static void main(String[] args) {
System.out.println(A.m);
} }
class A {
static { m = 300;
}
static int m = 100;
}
//第二步:链接结束后m=0
//第三步:初始化后,m的值由<clinit>()方法执行决定
// 这个A的类构造器<clinit>()方法由类变量的赋值和静态代码块中的语句按照顺序合并产生,类似于
// <clinit>(){
// m = 300;
// m = 100;
// }
Copy after login
1.3 了解:什么时候会发生类初始化?

类的主动引用(一定会发生类的初始化)

  1. 当虚拟机启动,先初始化main方法所在的类

  2. new一个类的对象

  3. 调用类的静态成员(除了final常量)和静态方法

  4. 使用java.lang.reflect包的方法对类进行反射调用

  5. 当初始化一个类,如果其父类没有被初始化,则先会初始化它的父类

类的被动引用(不会发生类的初始化)

  1. 当访问一个静态域时,只有真正声明这个域的类才会被初始化

  2. 当通过子类引用父类的静态变量,不会导致子类初始化

  3. 通过数组定义类引用,不会触发此类的初始化

  4. 引用常量不会触发此类的初始化(常量在链接阶段就存入调用类的常量池中了)

1.4 类加载器的作用

类加载的作用:将class文件字节码内容加载到内存中,并将这些静态数据转换成方法区的运行时数据结构,然后在堆中生成一个代表这个类的java.lang.Class对象,作为 方法区中类数据的访问入口。
类缓存:标准的JavaSE类加载器可以按要求查找类,但一旦某个类被加载到类加载器 中,它将维持加载(缓存)一段时间。不过JVM垃圾回收机制可以回收这些Class对象。

What is the concept of java reflection mechanism and how to use it

1.5 JVM中不同类型的类的加载器

What is the concept of java reflection mechanism and how to use it

1.6 代码演示

不同类型的类的加载器:

 @Test
    public void test1(){
        //对于自定义类,使用系统类加载器进行加载
        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
        System.out.println(classLoader);//sun.misc.Launcher$AppClassLoader@18b4aac2:系统类加载器
        //调用系统类加载器的getParent():获取扩展类加载器
        ClassLoader classLoader1 = classLoader.getParent();
        System.out.println(classLoader1);//sun.misc.Launcher$ExtClassLoader@279f2327:扩展类加载器
        //调用扩展类加载器的getParent():无法获取引导类加载器
        //引导类加载器主要负责加载java的核心类库,无法加载自定义类的。
        ClassLoader classLoader2 = classLoader1.getParent();
        System.out.println(classLoader2);//null

        ClassLoader classLoader3 = String.class.getClassLoader();
        System.out.println(classLoader3);//null

    }
Copy after login

使用系统类加载器读取Properties配置文件。

 /*
    Properties:用来读取配置文件。

     */
    @Test
    public void test2() throws Exception {

        Properties pros =  new Properties();
        //此时的文件默认在当前的module下。
        //读取配置文件的方式一://        FileInputStream fis = new FileInputStream("jdbc.properties");//        FileInputStream fis = new FileInputStream("src\\jdbc1.properties");//        pros.load(fis);

        //读取配置文件的方式二:使用ClassLoader
        //配置文件默认识别为:当前module的src下
        ClassLoader classLoader = ClassLoaderTest.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("jdbc1.properties");
        pros.load(is);


        String user = pros.getProperty("user");
        String password = pros.getProperty("password");
        System.out.println("user = " + user + ",password = " + password);
    }}
Copy after login

2. 何为Class类?

Class类在Object类中定义了以下的方法,此方法将被所有子类继承:

public final Class getClass()
Copy after login

以上的方法返回值的类型是一个Class类,此类是Java反射的源头,实际上所谓反射从程序的运行结果来看也很好理解,即:可以通过对象反射求出类的名称。

What is the concept of java reflection mechanism and how to use it

对象照镜子后可以得到的信息:某个类的属性、方法和构造器、某个类到底实现了哪些接口。对于每个类而言,JRE 都为其保留一个不变的Class类型的对象。
一个 Class对象包含了特定某个结构(class/interface/enum/annotation/primitivetype/void/[])的有关信息。

Class本身也是一个类

Class 对象只能由系统建立对象

一个加载的类在 JVM中只会有一个Class实例

一个Class对象对应的是一个加载到JVM中的一个.class文件

每个类的实例都会记得自己是由哪个Class 实例所生成

通过Class可以完整地得到一个类中的所有被加载的结构

Class类是Reflection的根源,针对任何你想动态加载、运行的类,唯有先获得相应的

3. Common methods of Class class

Call the default constructor and return an instance of the Returns the name of the entity (class, interface, array class, basic type or Returns the #Class [] getInterfaces()ClassClassLoader getClassLoader()Class getSuperclass()ClassConstructor[] getConstructors()ConstructorField[] getDeclaredFields()Field##Method getMethod(String name,Class … paramTypes)Object, the formal parameter type of this object is

3. 哪些类型可以有Class对象?

(1)class: 外部类,成员(成员内部类,静态内部类),局部内部类,匿名内部类
(2)interface:接口
(3)[]:数组
(4)enum:枚举
(5)annotation:注解@interface
(6)primitive type:基本数据类型
(7)void

三、获取Class类实例的四种方法

1. 调用运行时类的属性:.class

前提:若已知具体的类,通过类的class属性获取,该方法最为安全可靠, 程序性能最高
示例: Class clazz1 = String.class;

2. 通过运行时类的对象,调用getClass()

前提:已知某个类的实例,调用该实例的getClass()方法获取Class对象
示例:Class clazz = “www.atguigu.com”.getClass();

3.调用Class的静态方法:forName(String classPath)

前提:已知一个类的全类名,且该类在类路径下,可通过Class类的静态方法forName() 获取,可能抛出ClassNotFoundException
示例: Class clazz = Class.forName(“java.lang.String”);

4. 使用类的加载器:ClassLoader

示例:
ClassLoader cl = this.getClass().getClassLoader();
Class clazz4 = cl.loadClass(“类的全类名”);

5. 代码演示

@Testpublic void test1() throws ClassNotFoundException {
            //方式一:调用运行时类的属性:.class
            Class clazz1 = Person.class;
            System.out.println(clazz1);//class com.jiaying.java1.Person
            //方式二:通过运行时类的对象,调用getClass()
            Person p1 = new Person();
            Class clazz2 = p1.getClass();
            System.out.println(clazz2);//class com.jiaying.java1.Person

            //方式三:调用Class的静态方法:forName(String classPath)
            Class clazz3 = Class.forName("com.jiaying.java1.Person");
            Class clazz5 = Class.forName("java.lang.String");
            System.out.println(clazz3);//class com.jiaying.java1.Person
            System.out.println(clazz5);//class java.lang.String

            System.out.println(clazz1 == clazz2);//true
            System.out.println(clazz1 == clazz3);//true

            //方式四:使用类的加载器:ClassLoader  (了解)
            ClassLoader classLoader = ReflectionTest.class.getClassLoader();
            Class clazz4 = classLoader.loadClass("com.jiaying.java1.Person");
            System.out.println(clazz4);//class com.jiaying.java1.Person
            System.out.println(clazz1 == clazz4);//true}
Copy after login

四、 创建运行时类的对象

1. 引入

有了Class对象,能做什么?

创建类的对象:调用Class对象的newInstance()方法
要求:

  1. 类必须有一个无参数的构造器。

  2. 类的构造器的访问权限需要足够。

难道没有无参的构造器就不能创建对象了吗?
不是!只要在操作的时候明确的调用类中的构造器,并将参数传递进去之后,才可以实例化操作。
步骤如下:

  1. 通过Class类的getDeclaredConstructor(Class … parameterTypes)取得本类的指定形参类型的构造器

  2. 向构造器的形参中传递一个对象数组进去,里面包含了构造器中所需的各个参数。

  3. 通过Constructor实例化对象。

2. 语法步骤

(1)根据全类名获取对应的Class对象

String name = “atguigu.java.Person";Class clazz = null;clazz = Class.forName(name);
Copy after login

(2)调用指定参数结构的构造器,生成Constructor的实例

Constructor con = clazz.getConstructor(String.class,Integer.class);
Copy after login

(3)通过Constructor的实例创建对应类的对象,并初始化类属性

Person p2 = (Person) con.newInstance("Peter",20);System.out.println(p2);
Copy after login

3. 代码演示

 @Test
    public void test1() throws IllegalAccessException, InstantiationException {

        Class<Person> clazz = Person.class;
        /*
        newInstance():调用此方法,创建对应的运行时类的对象。内部调用了运行时类的空参的构造器。

        要想此方法正常的创建运行时类的对象,要求:
        1.运行时类必须提供空参的构造器
        2.空参的构造器的访问权限得够。通常,设置为public。


        在javabean中要求提供一个public的空参构造器。原因:
        1.便于通过反射,创建运行时类的对象
        2.便于子类继承此运行时类时,默认调用super()时,保证父类有此构造器

         */
        Person obj = clazz.newInstance();
        System.out.println(obj);

    }
Copy after login

4. 体会反射的动态性

//体会反射的动态性
    @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();
    }}
Copy after login

五、获取运行时类的完整结构

提供具有丰富内容的Person

//接口public interface MyInterface {
    void info();}//注解@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {
    String value() default "hello";}//父类public class Creature<T> implements Serializable {
    private char gender;
    public double weight;

    private void breath(){
        System.out.println("生物呼吸");
    }

    public void eat(){
        System.out.println("生物吃东西");
    }}//Person类@MyAnnotation(value="hi")public class Person extends Creature<String> implements Comparable<String>,MyInterface{

    private String name;
    int age;
    public int id;

    public Person(){}

    @MyAnnotation(value="abc")
    private Person(String name){
        this.name = name;
    }

     Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    @MyAnnotation
    private String show(String nation){
        System.out.println("我的国籍是:" + nation);
        return nation;
    }

    public String display(String interests,int age) throws NullPointerException,ClassCastException{
        return interests + age;
    }


    @Override
    public void info() {
        System.out.println("我是一个人");
    }

    @Override
    public int compareTo(String o) {
        return 0;
    }

    private static void showDesc(){
        System.out.println("我是一个可爱的人");
    }

    @Override
    public String toString() {
        return "Person{" +
                "name=&#39;" + name + &#39;\&#39;&#39; +
                ", age=" + age +
                ", id=" + id +
                &#39;}&#39;;
    }}
Copy after login

1. 获取当前运行时类的属性结构

Method nameFunction description
static Class forName(String name)Returns the Class object# of the specified class name name
##Object newInstance()Class object
getName()void) represented by this Class object
Class getSuperClass()Class object## of the parent class of the current Class object
Get the interface of the current object
Returns the class loader of this class
Returns the Class representing the superclass of the entity represented by this
Return an array containing some objects
Return An array of objects
Returns a MethodparamType
方法作用
public Field[] getFields()返回此Class对象所表示的类或接口的publicField
public Field[] getDeclaredFields()返回此Class对象所表示的类或接口的全部Field
  • Field方法中:

方法作用
public int getModifiers()以整数形式返回此Field的修饰符
public Class<?> getType()得到Field的属性类型
public String getName()返回Field的名称
    @Test
    public void test1(){

        Class clazz = Person.class;

        //获取属性结构
        //getFields():获取当前运行时类及其父类中声明为public访问权限的属性
        Field[] fields = clazz.getFields();
        for(Field f : fields){
            System.out.println(f);
        }
        System.out.println();

        //getDeclaredFields():获取当前运行时类中声明的所有属性。(不包含父类中声明的属性)
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field f : declaredFields){
            System.out.println(f);
        }
    }

    //权限修饰符  数据类型 变量名
    @Test
    public void test2(){
        Class clazz = Person.class;
        Field[] declaredFields = clazz.getDeclaredFields();
        for(Field f : declaredFields){
            //1.权限修饰符
            int modifier = f.getModifiers();
            System.out.print(Modifier.toString(modifier) + "\t");

            //2.数据类型
            Class type = f.getType();
            System.out.print(type.getName() + "\t");

            //3.变量名
            String fName = f.getName();
            System.out.print(fName);

            System.out.println();
        }
    }}
Copy after login

2. 获取当前运行时类的方法结构

方法作用
public Method[] getMethods()返回此Class对象所表示的类或接口的public的方法
public Method[] getDeclaredMethods()返回此Class对象所表示的类或接口的全部方法
  • Method类中:

方法作用
public Class<?> getReturnType()取得全部的返回值
public Class<?>[] getParameterTypes()取得全部的参数
public int getModifiers()取得修饰符
public Class<?>[] getExceptionTypes()取得异常信息
    @Test
    public void test1(){

        Class clazz = Person.class;

        //getMethods():获取当前运行时类及其所有父类中声明为public权限的方法
        Method[] methods = clazz.getMethods();
        for(Method m : methods){
            System.out.println(m);
        }
        System.out.println();
        //getDeclaredMethods():获取当前运行时类中声明的所有方法。(不包含父类中声明的方法)
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for(Method m : declaredMethods){
            System.out.println(m);
        }
    }
  /*
    @Xxxx
    权限修饰符  返回值类型  方法名(参数类型1 形参名1,...) throws XxxException{}
     */
    @Test
    public void test2(){
        Class clazz = Person.class;
        Method[] declaredMethods = clazz.getDeclaredMethods();
        for(Method m : declaredMethods){
            //1.获取方法声明的注解
            Annotation[] annos = m.getAnnotations();
            for(Annotation a : annos){
                System.out.println(a);
            }

            //2.权限修饰符
            System.out.print(Modifier.toString(m.getModifiers()) + "\t");

            //3.返回值类型
            System.out.print(m.getReturnType().getName() + "\t");

            //4.方法名
            System.out.print(m.getName());
            System.out.print("(");
            //5.形参列表
            Class[] parameterTypes = m.getParameterTypes();
            if(!(parameterTypes == null && parameterTypes.length == 0)){
                for(int i = 0;i < parameterTypes.length;i++){

                    if(i == parameterTypes.length - 1){
                        System.out.print(parameterTypes[i].getName() + " args_" + i);
                        break;
                    }

                    System.out.print(parameterTypes[i].getName() + " args_" + i + ",");
                }
            }

            System.out.print(")");

            //6.抛出的异常
            Class[] exceptionTypes = m.getExceptionTypes();
            if(exceptionTypes.length > 0){
                System.out.print("throws ");
                for(int i = 0;i < exceptionTypes.length;i++){
                    if(i == exceptionTypes.length - 1){
                        System.out.print(exceptionTypes[i].getName());
                        break;
                    }

                    System.out.print(exceptionTypes[i].getName() + ",");
                }
            }


            System.out.println();
        }



    }}
Copy after login

3. 获取当前运行时类的构造器结构

方法作用
public Constructor<T>[] getConstructors()返回此 Class 对象所表示的类的所有public构造方法。
public Constructor<T>[] getDeclaredConstructors()返回此 Class 对象表示的类声明的所有构造方法。
  • Constructor类中:

方法作用
public int getModifiers()取得修饰符
public String getName()取得方法名称
public Class<?>[] getParameterTypes()取得参数的类型
/*
    获取构造器结构

     */
    @Test
    public void test1(){

        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);
        }

    }
 /*
    获取运行时类的父类

     */
    @Test
    public void test2(){
        Class clazz = Person.class;

        Class superclass = clazz.getSuperclass();
        System.out.println(superclass);
    }

    /*
    获取运行时类的带泛型的父类

     */
    @Test
    public void test3(){
        Class clazz = Person.class;

        Type genericSuperclass = clazz.getGenericSuperclass();
        System.out.println(genericSuperclass);
    }

    /*
    获取运行时类的带泛型的父类的泛型


    代码:逻辑性代码  vs 功能性代码
     */
    @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());
    }/*
    获取运行时类实现的接口
     */
    @Test
    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);
        }

    }
    /*
        获取运行时类所在的包

     */
    @Test
    public void test6(){
        Class clazz = Person.class;

        Package pack = clazz.getPackage();
        System.out.println(pack);
    }

    /*
        获取运行时类声明的注解

     */
    @Test
    public void test7(){
        Class clazz = Person.class;

        Annotation[] annotations = clazz.getAnnotations();
        for(Annotation annos : annotations){
            System.out.println(annos);
        }
    }}
Copy after login

六、调用运行时类的指定结构

关于setAccessible方法的使用

MethodFieldConstructor对象都有setAccessible()方法。

setAccessible启动和禁用访问安全检查的开关。

参数值为true则指示反射的对象在使用时应该取消Java语言访问检查。

提高反射的效率。如果代码中必须用反射,而该句代码需要频繁的被 调用,那么请设置为true,使得原本无法访问的私有成员也可以访问,参数值为false则指示反射的对象应该实施Java语言访问检查。

1. 调用运行时类中指定的属性

在反射机制中,可以直接通过Field类操作类中的属性,通过Field类提供的set()get()方法就可以完成设置和取得属性内容的操作。

方法作用
public Field getField(String name)返回此Class对象表示的类或接口的指定的publicField
public Field getDeclaredField(String name)返回此Class对象表示的类或接口的指定的Field

在Field中:

方法作用
public Object get(Object obj)取得指定对象obj上此Field的属性内容
public void set(Object obj,Object value)设置指定对象obj上此Field的属性内容

代码演示:

public class ReflectionTest {
    @Test
    public void testField() throws Exception {
        Class clazz = Person.class;

        //创建运行时类的对象
        Person p = (Person) clazz.newInstance();


        //获取指定的属性:要求运行时类中属性声明为public
        //通常不采用此方法
        Field id = clazz.getField("id");

        /*
        设置当前属性的值

        set():参数1:指明设置哪个对象的属性   参数2:将此属性值设置为多少
         */

        id.set(p,1001);

        /*
        获取当前属性的值
        get():参数1:获取哪个对象的当前属性值
         */
        int pId = (int) id.get(p);
        System.out.println(pId);


    }
    /*
    如何操作运行时类中的指定的属性 -- 需要掌握
     */
    @Test
    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));
    }
Copy after login

2. 调用运行时类中的指定的方法

通过反射,调用类中的方法,通过Method类完成。步骤:

  1. 通过Class类的getMethod(String name,Class…parameterTypes)方法取得 一个Method对象,并设置此方法操作时所需要的参数类型。

  2. 之后使用Object invoke(Object obj, Object[] args)进行调用,并向方法中 传递要设置的obj对象的参数信息。

What is the concept of java reflection mechanism and how to use it

Object invoke(Object obj, Object … args)
说明:
Object 对应原方法的返回值,若原方法无返回值,此时返回null

若原方法若为静态方法,此时形参Object obj可为null

若原方法形参列表为空,则Object[] argsnull
若原方法声明为private,则需要在调用此invoke()方法前,显式调用 方法对象的setAccessible(true)方法,将可访问private的方法。

代码演示:

 /*
    如何操作运行时类中的指定的方法 -- 需要掌握
     */
    @Test
    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("*************如何调用静态方法*****************");

        // private static void showDesc()

        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //如果调用的运行时类中的方法没有返回值,则此invoke()返回null//        Object returnVal = showDesc.invoke(null);
        Object returnVal = showDesc.invoke(Person.class);
        System.out.println(returnVal);//null

    }
Copy after login

3. 调用运行时类中的指定的构造器

代码演示:

  /*
    如何调用运行时类中的指定的构造器
     */
    @Test
    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);

    }}
Copy after login


The above is the detailed content of What is the concept of java reflection mechanism and how to use it. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template