相关文章推荐
仗义的沙发  ·  AWS S3 ...·  2 年前    · 
小眼睛的羊肉串  ·  python3 os.system ...·  2 年前    · 
千杯不醉的黑框眼镜  ·  c++ - ...·  2 年前    · 

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

}

此例子的运行结果:

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

Method Class.getMethod(String name, Class... parameterTypes)的作用是获得对象所声明的公开方法该方法的第一个参数name是要获得方法的名字,第二个参数parameterTypes是按声明顺序标识该方法形参类型。person.getClass().getMethod("Speak", null);//获得person对象的Sp
public &lt;E extends Exception,T1,T2,TR extends ArrayList&lt; String &gt;&gt; TR testGeneric(Test this, T1 a1, T2 a2) throws IndexOutOfBoundsException,E { return (TR) new ArrayList&lt; String &gt;();
Method get Method ( String name, Class ... parameter Types ) --返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。 方法后面接收的就是 Class 类的对象,而如: String . class 、int. class 这些字节码才是 Class 类的对象 也可以此种方式: //get Method 第一个
反射 的get Method 方法get Method ( String name, Class <?>… parameter Types ) Class <?>… parameter Types 表示需要执行的方法 Method 参数 类型,及invoke里面传入的实例 参数 是那些,多个 参数 的话就传多个 参数 类型 对于传入可变 参数 ,我们可以有两种传法,不做多余的讲述,看代码 public class FanShe { public static void main( String [] args) thro
我们在前面的源码过程中,了解了springfox的基本工作原理,接下来,我们可以通过使用springfox给我们提供的外部接口,来处理一些我们工作中碰到的问题,或者进行自定义扩展 本篇主要介绍如何来忽略某些特定的 参数 Class 类型 先举一个例子,假如我们的接口是这样的: @PostMapping("/createOr33der") @ApiOperation(value = "创建订单...
JAVA 反射 机制 JAVA 反射 机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为 java 语言的 反射 机制。 Java 反射 机制主要提供了以下功能: 在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法;在运行时调用任意一