一、Method类
代表类中的一个方法的定义,一个Method由修饰符,返回值,方法名称,参数列表组合而成。
二、Method提供的方法
1、getName();获得方法名。
2、getModifiers();获得修饰符。
3、getReturnTypes();返回值类型。返回class
4、getParameterTypes();返回Class[],参数类型的数组。
5、invoke(Object obj,Object…args);
三、如何获得Method呢?
1、Class方法。
2、Method GetMethod(String name,Class<?>...args);
3、Method[] getMethod();获得所有的公共方法。
4、Method getDeclaredMethod(String name,Class...args);根据名称和参数获得对应的方法。
5、Method[] getDeclaredMethods();获得当前类中定义的所有方法。

Person类
package com.imooc.reflect.test; / * ClassName Person * * @Description: TODO * @Author 陆小涛 * @Date 2020/8/21 16:06 * @Version 1.0 */ public class Person {
public String name; private String sex; public Person(){
} public Person(String name, String sex) {
this.name = name; this.sex = sex; } public String getName() {
return name; } public void setName(String name) {
this.name = name; } public String getSex() {
return sex; } public void setSex(String sex) {
this.sex = sex; } public void eat(){
System.out.println("....吃"); } private void run(){
System.out.println("跑"); } private String sayHello(String name){
return name; } @Override public String toString() {
return "Person{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + '}'; } }
讯享网
1、测试公有的方法
讯享网 @Test //测试公有的方法 public void demo01() throws Exception {
//反射到这个类 Class<Person> class1 = (Class<Person>) Class.forName("com.imooc.reflect.test.Person"); //实例化 Person person =class1.newInstance(); //获得公有的方法 Method method = class1.getMethod("eat"); //执行该方法 method.invoke(person); }
运行结果

2、测试私有的方法
@Test //测试私有的方法 public void demo02() throws Exception{
//反射到这个类 Class<Person> class1 = (Class<Person>) Class.forName("com.imooc.reflect.test.Person"); //实例化 Person person =class1.newInstance(); //获得公有的方法 Method method = class1.getDeclaredMethod("run"); //设置私有的方法的访问权限 method.setAccessible(true); //执行该方法 method.invoke(person); }
运行结果

3、测试私有的方法带参
讯享网@Test //测试私有的方法带参数的 public void demo03() throws Exception{
//反射到这个类 Class<Person> class1 = (Class<Person>) Class.forName("com.imooc.reflect.test.Person"); //实例化 Person person =class1.newInstance(); //获得公有的方法 Method method = class1.getDeclaredMethod("sayHello", String.class); //设置私有的方法的访问权限 method.setAccessible(true); //执行该方法(返回的OBJ类型的)这里因为我知道返回的是String.所以进行了强转。 String str = (String) method.invoke(person,"你好"); System.out.println(str); } }
运行结果


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/40219.html