1.如何获取某个方法

方法的名称和方法的参数列表才能唯一决定一个方法

2.方法反射的操作

method.invoke();

package com.tsh.reflect;

import java.lang.reflect.Method;


public class ReflectDemo {
    public static void main(String[] args) {
        P p=new P();
        Class c=P.class;
        try {
            Method method=c.getDeclaredMethod("print", String.class);
            method.invoke(p, "ssss");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
class P{
    public void print(int a,int b){
        System.out.println(a+b);
    }
    public void print(String a){
        System.out.println(a);
    }
                                 
}

如果方法是private的会报这个错误

 java.lang.IllegalAccessException

 

相关文章:

  • 2022-12-23
  • 2022-01-06
  • 2021-07-27
  • 2021-10-31
  • 2021-09-22
  • 2022-12-23
  • 2021-12-10
  • 2021-09-21
猜你喜欢
  • 2021-07-23
  • 2021-12-10
  • 2021-08-05
  • 2021-08-04
  • 2021-07-25
  • 2021-11-07
  • 2021-12-10
相关资源
相似解决方案