zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Java 反射调用方法实例,动态动用方法实例

JAVA实例方法反射 动态 调用
2023-09-11 14:14:47 时间

包结构

 

Hello.java

package test;

public class Hello {
    public double add (double score1, double score2){
        return score1 + score2;
    }

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

    public static double mul(double score1, double score2){
        return score1 * score2;
    }
}

 

CalculatorTest.java

package test;

import java.lang.reflect.Method;


class Calculator{
    public Calculator(){
        //这个构造器仅有一个参数:name
        System.out.println("Calculator 构造函数");
    }

    public String eDIo(String str){
        String str_temp = "";
        str_temp = str.replace("World", "Hello");
        return str_temp;
    }
}

public class CalculatorTest {
    public static void main(String[] args) throws Exception {
        Calculator cal = new Calculator();
        String str_class_name = cal.eDIo("test.World");

        //方法一:通过类的.class属性获取
        //Class<Hello> clz = Hello.class;
        //方法二:通过类的完整路径获取,这个方法由于不能确定传入的路径是否正确,这个方法会抛ClassNotFoundException
        Class clz = Class.forName(str_class_name);
        //方法三:new一个实例,然后通过实例的getClass()方法获取
        //Hello s = new Hello();
        //Class<Hello> clz = s.getClass();
        //1. 获取类中带有方法签名的mul方法,getMethod第一个参数为方法名,第二个参数为mul的参数类型数组
        Method method = clz.getMethod("mul", new Class[]{double.class, double.class});
        //invoke 方法的第一个参数是被调用的对象,这里是静态方法故为null,第二个参数为给将被调用的方法传入的参数
        Object result = method.invoke(null, new Object[]{2.0, 2.5});
        //如果方法mul是私有的private方法,按照上面的方法去调用则会产生异常NoSuchMethodException,这时必须改变其访问属性
        //method.setAccessible(true);//私有的方法通过发射可以修改其访问权限
        System.out.println(result);//结果为5.0
        //2. 获取类中的非静态方法
        Method method_2 = clz.getMethod("add", new Class[]{double.class, double.class});
        //这是实例方法必须在一个对象上执行
        Object result_2 = method_2.invoke(new Hello(), new Object[]{2.0, 2.5});
        System.out.println(result_2);//4.5
        //3. 获取没有方法签名的方法print
        Method method_3 = clz.getMethod("print", new Class[]{});
        Object result_3 = method_3.invoke(new Hello(), null);//result_3为null,该方法不返回结果
    }
}

 

运行结果

Calculator 构造函数
5.0
4.5
OK