NoSuchMethodException反射异常处理

NoSuchMethodException意思是没有找到该方法。反射异常处理,记录下出现这个异常的原因

实体类

import lombok.Data;

@Data
public class Student {
    private Long age;
    private String name;
}

控制类

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test01 {
    public static void main(String[] args) {
        Test01 test01 = new Test01();
        test01.getName(new Student());
    }

    public <T> void getName(T tClass){
        Method[] declaredMethods = tClass.getClass().getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }

        try {
            Method setAge = tClass.getClass().getDeclaredMethod("setAge");
            setAge.setAccessible(true);
        } catch (NoSuchMethodException  e) {
            e.printStackTrace();
        }
    }
}

控制台

public boolean com.fanshe.Student.equals(java.lang.Object)
public java.lang.String com.fanshe.Student.toString()
public int com.fanshe.Student.hashCode()
public java.lang.String com.fanshe.Student.getName()
public void com.fanshe.Student.setName(java.lang.String)
public java.lang.Long com.fanshe.Student.getAge()
public void com.fanshe.Student.setAge(java.lang.Long)
protected boolean com.fanshe.Student.canEqual(java.lang.Object)
java.lang.NoSuchMethodException: com.fanshe.Student.setAge()
	at java.lang.Class.getDeclaredMethod(Class.java:2130)
	at com.fanshe.Test01.getName(Test01.java:19)
	at com.fanshe.Test01.main(Test01.java:9)

报错原因可能如下

  • 查询的方法为私有的
  • 方法有入参,但是查询方法确没有传入参类型
  • 查询的方法不存在

题主的问题,获取带有入参的方法,未设置入参

解决:在反射查询方法第二个参数添加入参类型即可

Method setAge = tClass.getClass().getDeclaredMethod("setAge",Long.class);
posted @ 2021-12-31 17:01  HeiDaotu  阅读(2534)  评论(0编辑  收藏  举报