Method Class.getMethod(String name, Class<?>... parameterTypes)的做用是得到對象所聲明的公開方法java
該方法的第一個參數name是要得到方法的名字,第二個參數parameterTypes是按聲明順序標識該方法形參類型。this
person.getClass().getMethod("Speak", null);.net
//得到person對象的Speak方法,由於Speak方法沒有形參,因此parameterTypes爲null對象
person.getClass().getMethod("run", String.class);blog
//得到person對象的run方法,由於run方法的形參是String類型的,因此parameterTypes爲String.classget
若是對象內的方法的形參是int類型的,則parameterTypes是int.classio
本人寫了一個例子來幫助你們來理解此方法的做用:class
Person類:test
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類:import
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