通过反射得到类中的方法,并调用。

简介

一般创建对象时,我们需要直接new类的对对象,这种编程方式称为硬编码(代码写死了),为了后期程序的可扩展,开发中通常采用实例内的完整限定名(包名.类名)。通过反射加载字符串指定的类,并通过反射创建对象,得到类中的基本信息。

new方法是编译期静态加载对象,需要保证编译时对象就存在且正确。使用类的类类型来加载对象是动态加载对象,运行时正确即可。

得到类中的方法

1.创建一个类Students

package Reflect;

public class Students {
    public Students() {    }

    public void show(int num,String str){
        System.out.println("秀一下"+num+" "+str);
    }
    private void print(){
        System.out.println("输出!");
    }

    public String dome(String str,int num){
        return str+" "+num;
    }
}

2.创建一个测试类StudentText

package Reflect;


import java.lang.reflect.Method;

public class StudentText {
    public static void main(String[] args) throws Exception {
        Class stu=Class.forName("Reflect.Students");//得到类类型

        Object newInstance = stu.newInstance();//得到Students的无参构造函数

        //根据方法名和参数类型得到指定方法  方法名   参数类型  参数类型
        Method show=stu.getMethod("show", int.class, String.class);//得到共有方法
        //调用方法   指定对象       参数   参数
        show.invoke(newInstance,20,"嗨燊");

        Method print=stu.getDeclaredMethod("print");//得到指定的公有或私有方法
        print.setAccessible(true);//设置为可调用私有方法
        print.invoke(newInstance);

        Method dome=stu.getMethod("dome", String.class, int.class);
        Object invoke = dome.invoke(newInstance, "20", 90);//有返回值的方法
        System.out.println(invoke);
    }
}

3.输出结果


不管是私有还是公有的方法,都可以通过反射得到,然后调用。setAccessible()方法的作用是:将此对象的accessible标记设置位指定的布尔值,true的值表示反射对象应该在使用时抑制Java语言访问检查。false(默认值)的值表示反射的对象应该强制执行Java语言访问检查。当你访问对象中的私有成员时,Java语言检查会阻止,所以要改为true。


       每日鸡汤:今天的每一点小事都将积累成你未来的大事!


Over!

猜你喜欢

转载自blog.csdn.net/chianz632/article/details/80299512