Method invoke method implemented in java reflection of

Some common examples java reflection

package cn.com;

import java.lang.reflect.Method;

/**
 * Copyright (C), 2018-2019
 *
 * @Description: TODO
 * @Author: zhou
 * @Create: 2019/10/10 16:36
 * @Version 1.0.0
 */

public class MethodInvoke {
    public static void main(String[] args) throws Exception {

        Class implClass = Class.forName("cn.com.Animal");
        Object instance = implClass.newInstance(); // 实例
        System.out.println("instance:" + instance);
        Method method = instance.getClass().getMethod("print");
        method.invoke(instance);

        Method method1 = implClass.getDeclaredMethod("print");
        method1.invoke(instance);

        Method animalMethod = Animal.class.getDeclaredMethod("print");
        Method catMethod = Cat.class.getDeclaredMethod("print");

        Animal animal = new Animal();
        Cat cat = new Cat();
        animalMethod.invoke(cat);
        animalMethod.invoke(animal);
        System.out.println("=====");
        catMethod.invoke(cat);
        catMethod.invoke(animal);
    }
}

class Animal {

    public void print() {
        System.out.println("Animal.print()");
    }
    
}

class Cat extends Animal {

    @Override
    public void print() {
        System.out.println("Cat.print()");
    }

}

 

The method of obtaining the reflection are:

The first: 
Class = Animal Animal.class;
The second: 
Class = Animal the Class.forName ( "cn.com.Animal"); // Animal class full path
After acquiring the Class, you will be able to get there is reference method
Method method = animal.getDeclaredMethod(String name, Class<?>... parameterTypes);
. Method, Method Animal = getMethod (String name, Class ... The parameterTypes <?>); 
Wherein: name is the name of the method, the method of parameter types paramterTypers

by = Animal instance Object.
The newInstance (); instantiate the class

Finally,
Method.invoke (instance, parameValue); 
instance of the class is instantiated, paramValue a method parameter (according to the actual incoming)

Java reflection can not access the private methods bypass restrictions
 

 

Guess you like

Origin www.cnblogs.com/zhou-h/p/11649305.html