zoukankan      html  css  js  c++  java
  • java中Class.getMethod方法

    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

    本人写了一个例子来帮助大家来理解此方法的作用:

    Person类:

    package fyh.reflectDemo;
    public class Person {
        private String name;
        private int ID;
        public String speed;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getID() {
            return ID;
        }
        public void setID(int iD) {
            ID = iD;
        }
        public Person(String name,int ID){
            this.name = name;
            this.ID = ID;
        }
        public void Speak(){
            System.out.println("Hello! "+"My name is "+name);
        }
        public void run(String speed){
            System.out.println("I can run " + speed+" KM!!!");
        }
        
    }

    testMain类:

    package fyh.reflectDemo;
    import java.lang.reflect.Method;
    public class testMain {        
        public static void main(String[] args) throws Exception {        
            Person person = new Person("小明",10001);
            person.Speak();
            person.run("10");
            Method m1 = person.getClass().getMethod("Speak", null);        
            Method m2 = person.getClass().getMethod("run", String.class);
            System.out.println(m1);
            System.out.println(m2);
        }

    }

    本文转自: https://blog.csdn.net/Handsome_fan/article/details/54846959

  • 相关阅读:
    POJ 3630
    Codeforces Round #219 (Div. 2) D题
    Codeforces Round #232 (Div. 2) On Sum of Fractions
    Codeforces Round #232 (Div. 2) C
    撸呀撸的左手(KMP+DP)
    hdu poj KMP简单题目总结
    LCT总结
    bzoj1019 [SHOI2008]汉诺塔
    NOIP2016总结
    p1199八数码问题
  • 原文地址:https://www.cnblogs.com/fpqi/p/9618218.html
Copyright © 2011-2022 走看看