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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM