java中methods方法_java中Class.getMethod方法
Method Class.getMethod(String name, Class>... parameterTypes)的作用是獲得對象所聲明的公開方法
該方法的第一個參數(shù)name是要獲得方法的名字,第二個參數(shù)parameterTypes是按聲明順序標識該方法形參類型。
person.getClass().getMethod("Speak", null);
//獲得person對象的Speak方法,因為Speak方法沒有形參,所以parameterTypes為null
person.getClass().getMethod("run", String.class);
//獲得person對象的run方法,因為run方法的形參是String類型的,所以parameterTypes為String.class
如果對象內(nèi)的方法的形參是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);
}
}
本文轉(zhuǎn)自:?https://blog.csdn.net/Handsome_fan/article/details/54846959
總結(jié)
以上是生活随笔為你收集整理的java中methods方法_java中Class.getMethod方法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php pdo 关闭,php pdo预
- 下一篇: python打开文件_用Python(i