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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM