java反射之Method的invoke方法实现

java反射常用的一些实例

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

}

获取反射的方法有:

第一种:
Class animal =Animal.class;
第二种:
Class animal = Class.forName("cn.com.Animal"); // Animal类的全路径
获取到 Class 之后,便可以获取有参方法
Method method = animal.getDeclaredMethod(String name, Class<?>... parameterTypes);
Method method = animal.getMethod(String name, Class<?>... parameterTypes); 
其中: name 为方法名,paramterTypers方法的参数类型

可以通过 Object instance = animal.
newInstance(); 将类实例化

最后通过
method.invoke(instance, parameValue);
instance为类是实例化,paramValue为方法参数(根据实际情况传入)

java反射可饶过不能访问私有方法的限制
 

猜你喜欢

转载自www.cnblogs.com/zhou-h/p/11649305.html