Java反射之Method Class.getMethod(String name, Class<?>... parameterTypes)

The function of Method Class.getMethod(String name, Class<?>... parameterTypes) is to obtain the public method declared by the object

The first parameter name of the method is the name of the method to be obtained, and the second parameter parameterTypes identifies the method parameter types in the order of declaration.

person.getClass().getMethod("Speak", null);

//Get the Speak method of the person object, because the Speak method has no formal parameters, so parameterTypes is null

person.getClass().getMethod("run", String.class);

//Get the run method of the person object, because the formal parameter of the run method is of type String, so parameterTypes is String.class

If the parameters of the method inside the object are of type int, parameterTypes is int.class

I wrote an example to help you understand what this method does:

Person class:

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);
    }

}

此例子的运行结果:



在看不明白API文档说什么的时候,自己动手写一个例子就能明白了大笑


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325640283&siteId=291194637
Recommended