zoukankan      html  css  js  c++  java
  • 获取Methods成员方法类

    位于java.lang.reflect.Method包中

      getModifiers() 成员方法的修饰符
      getName() 成员方法的名字
      getReturnType() 成员方法的声明类型
      getParameterTypes() 成员方法的参数类型

    class.getMethods() 获取所有public公有成员方法
    class.getMethod(方法名,方法参数) 获取指定的public公有成员方法
    class.getDeclaredMethods() 获取所有成员方法
    class.getDeclaredMethods(方法名,方法参数) 获取指定的成员方法

    invoke(Object obj 对象, Object ... args 参数) 调用成员方法
        
    public class Demo {
        public static void main(String[] args) {
            try {
                Class c = Class.forName("Example");//创建Class对象
                Method ms[] = c.getDeclaredMethods();//获取所有成员方法
                for (Method m : ms) {
                    System.out.print(Modifier.toString(m.getModifiers()));//修饰符
                    System.out.print(" " + m.getReturnType().getSimpleName());//返回声明类型
                    Class paras[] = m.getParameterTypes();//参数类型
                    for (Class para : paras) {
                        System.out.print(" " + para.getSimpleName());
                    }
                    System.out.println();
                    //调用Example中add方法
                    Constructor cons = c.getConstructor();//获取Example中的构造方法
                    Object obj = cons.newInstance();//实例化
                    Method m2 = c.getDeclaredMethod("add", int.class, int.class);//获取add方法
                    m2.setAccessible(true);//获取private的权限
                    m2.invoke(obj, 1, 2);//调用成员方法
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    public class Example {
        private void add(int a,int b){
            System.out.println("a+b="+(a+b));
        }
    }
    
    
    
     
    
    
     
  • 相关阅读:
    Ftp、Ftps与Sftp之间的区别
    Previous Workflow Versions in Nintex Workflow
    Span<T>
    .NET Core 2.0及.NET Standard 2.0 Description
    Announcing Windows Template Studio in UWP
    安装.Net Standard 2.0, Impressive
    SQL 给视图赋权限
    Visual Studio for Mac中的ASP.NET Core
    How the Microsoft Bot Framework Changed Where My Friends and I Eat: Part 1
    用于Azure功能的Visual Studio 2017工具
  • 原文地址:https://www.cnblogs.com/xixixing/p/9553319.html
Copyright © 2011-2022 走看看