A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

Method类:它的实例对象代表某个类中的一个成员方法

代码实例:用反射调用String类的charAt方法

package com.reflection.method;

import java.lang.reflect.Method;

public class ReflectionGetMethod {
        public static void main(String[] args) {
                /**
                 * Method类,用反射获得一个对象的方法,并且调用该方法,用String类演示,调用charAt() 方法
                 * new String.charAt(2) 用反射实现
                 */
               
                String str = "abcdefg";
               
                Class cls = str.getClass();
               
                try {
                        //获取String类中的charAt(int index)方法对象     .getMethod获取单个具体的方法
                        Method methodCharAt = cls.getMethod("charAt", int.class);        //第一个参数为对象的方法名,第二参数为该方法的参数类型
                        System.out.println(methodCharAt.invoke(str, 2));                //方法对象.invoke方法,表示调用该方对象对象的底层方法
                } catch (Exception e) {
                        e.printStackTrace();
                }
        }
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马