反射中Method类的invoke() 和getMethod()[通俗易懂]

反射中Method类的invoke() 和getMethod()[通俗易懂]就是调用类中的方法,最简单的用法是可以把方法参数化。invoke(class,method);  MethodClass.getMethod(Stringname,Class<?>…parameterTypes)的作用是获得对象所声明的公开方法该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型…

大家好,又见面了,我是你们的朋友全栈君。

就是调用类中的方法,最简单的用法是可以把方法参数化。invoke(class, method);

 

 

Method Class.getMethod(String name, Class<?>… parameterTypes)的作用是获得对象所声明的公开方法

该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型。

person.getClass().getMethod(“Speak”, null);

//获得person对象的Speak方法,因为Speak方法没有形参,所以parameterTypes为null

person.getClass().getMethod(“run”, String.class);

//获得person对象的run方法,因为run方法的形参是String类型的,所以parameterTypes为String.class

如果对象内的方法的形参是int类型的,则parameterTypes是int.class

 

//getMethod第一个参数是方法名,第二个参数是该方法的参数类型,
//因为存在同方法名不同参数这种情况,所以只有同时指定方法名和参数类型才能唯一确定一个方法

 

Method method = XXX.getClass().getMethod(methodName,new Class[0]);

 //第一个参数是具体调用该方法的对象
 //第二个参数是执行该方法的具体参数反射中Method类的invoke() 和getMethod()[通俗易懂]    

 

如一个函数 int Test(int a, String str);

对应的getMethod方法:

1.  getMethod(“Test”,int.class,String.class);

2. getMethod(“Test”,new Class[]{int.class,String.class});

//Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,返回值总是对象。

 

 //如果参数为基本类型数据,必须转换为相应的包装类型的对象。

 

 

public Object invoke(Object obj,
                     Object... args)
              throws IllegalAccessException,
                     IllegalArgumentException,
                     InvocationTargetException

InvokeObj.java:

public class InvokeObj {

    public void show(){

        System.out.println(“无参show()方法”);
    }
    public void show(String name){

        System.out.println(“show方法:”+name);
    }
    public String[] arrayShow(String[] arr){

        return arr;
    }
    public String stringShow(String str){

        return str;
    }
    public int intShow(int sum){

        return sum;
    }
}
 

MethodInvokeTest.java:

 

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodInvokeTest {

    public static void main(String[] args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {

        
        Class<InvokeObj> clazz=InvokeObj.class;
        Method[] methods=clazz.getMethods();
        //输出了Class类型的所有方法。
        System.out.println(“以下输出InvokeObj类的方法”);
        for(Method method:methods){

            System.out.println(method);
        }
        System.out.println();
        
         System.out.println(“InvokeObj类的无参show()方法:”);
         Method method1=clazz.getMethod(“show”,null);
        //会执行无参show()方法
         Object obj=method1.invoke(new InvokeObj(),null);
         System.out.print(“输出无参show()方法的返回值:”+obj);
         System.out.println();System.out.println();
        
         System.out.println(“InvokeObj类的show()方法: “);  
         Method method2 = clazz.getMethod(“show”, String.class);
         Object obj1 = method2.invoke(new InvokeObj(), “hello,world”);  
           // System.out.println(“输出有参show()方法: “);
         System.out.println();
        
         System.out.println(“InvokeObj类的arrayShow()方法: “);  
         Method method3 = clazz.getMethod(“arrayShow”, String[].class);  
            String[] strs = new String[]{“hello”, “world”, “!”};  
            //数组类型的参数必须包含在new Object[]{}中,否则会报IllegalArgumentException  
            String[] strings = (String[]) method3.invoke(new InvokeObj(), new Object[]{strs});  
            for (String str : strings) {  
                System.out.println(“arrayShow的数组元素:” + str);  
            }
         System.out.println();   
        
         System.out.println(“InvokeObj类的StringShow()方法: “);  
            Method method4 = clazz.getMethod(“stringShow”, String.class);  
            String string = (String) method4.invoke(new InvokeObj(), “Thinking in java”);  
            System.out.println(“stringShow()方法的返回值: ” + string);  
            System.out.println();
            
            System.out.println(“InvokeObj类的intShow()方法: “);  
            Method method5 = clazz.getMethod(“intShow”, int.class);  
            int num = (Integer) method5.invoke(new InvokeObj(), 89);  
            System.out.println(“intShow()方法的返回值: ” + num);     
            
        
    }

}
反射中Method类的invoke() 和getMethod()[通俗易懂]

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/125281.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • source insight激活码3.5_source insight4.0安装

    source insight激活码3.5_source insight4.0安装SourceInsight3.x官方下载地址:http://www.sourceinsight.com/distribute/Si3563Setup.exe官方网站:http://www.sourceinsight.com/注册码:SI3US-230590-09757SI3US-840598-11493SI3US-404808-04697SI3US-510811-93484…

    2022年10月3日
    0
  • EPPLUS 分组

    EPPLUS 分组使用EPPLUS,导出的EXCEL文件中分组publicvoidRow_Col_Grouping_Test(){//http://stackoverflow.com/questions/32760210/how-to-group-rows-columns-in-epplus//Throwinsomedatavardatatable=newDa

    2022年6月23日
    28
  • Java之XML的使用「建议收藏」

    Java之XML的使用「建议收藏」一.xml的定义和优势:(1).定义:在描述一些有结构性的数据时应当使用XML来描述,例如:用户信息/省市结构等XML(eXtensibleMarkupLanguage),是一种可扩展的标记语言,类似HTML。XML技术是W3C组织(WorldWideWebConsortium万维网联盟)发布的,目前遵循的是W3C组织于1998年发布的XML1.0规范。HTML:显示页面,网…

    2022年7月7日
    22
  • JVM异常FGC问题查找过程总结

    JVM异常FGC问题查找过程总结问题现象及分析可能原因分析手动重现异常大对象问题流量暴涨CPU资源被其他进程占用内存被其他进程占用的情况swap分区问题数据库连接异常堆文件分析shell脚本JVM问题排查总结其他遗留的问题前段时间线上的zzuser的服务模块出现大量的异常FGC情况,经过大量排查工作,最后锁定是因为一个sql的大查询导致的。这也给了我非常大的教训,同时我在这次问题的排查过程中也获益匪浅,

    2022年6月19日
    29
  • 多参数sp_executesql 函数的使用范例

    多参数sp_executesql 函数的使用范例终于搞定sp_executesql包含输出的多参数的调用,网上竟然没有很好的参考   set@sql=Nselect@I_ZSL=sum(I_SL),@I_ZYZ=sum(I_YZ),@I_ZZJ=sum(I_LJZJ),@I_ZJZ=(sum(I_YZ)-sum(I_LJZJ))fromV_GZ_SGZ_GZINFO_TYBwhereV_DW_DM=

    2022年5月21日
    41
  • 高德地图自定义marker图片相关[通俗易懂]

    高德地图自定义marker图片相关[通俗易懂]Android高德地图自定义点聚合marker图片及Overlay点击选中功能关于高德地图添加Marker遇到的一些坑-m0_37295672的博客-CSDN博客http://blog.csdn.net/m0_37295672/article/details/77851580为地图marker设置网络图片-m00123456789的博客-CSDN博客htt…

    2022年5月11日
    37

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号