object is not an instance of declaring class

测试反射的时候报错了代码如下

package org.example.provider.domain;
import lombok.Data;
@Data
public class User {
    public int userId;
    public String userName;
}
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class cl = Class.forName("org.example.provider.domain.User");
        Method[] methods = cl.getMethods();
        System.out.println("methods.length:"+methods.length);
        for (Method method : methods) {
            System.out.println("method:"+method.getName());
            if(method.getName().equals("setUserId")){
                Object invoke = method.invoke(cl,1);
            }
        }
        System.out.println(cl);

    }

因为 method.invoke 方法的第一个参数是 实例对象 调用下 newInstance 就可以了

public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
        Class cl = Class.forName("org.example.provider.domain.User");
        Constructor constructor = cl.getDeclaredConstructor();
        Object o = constructor.newInstance();
        Method[] methods = cl.getMethods();for (Method method : methods) {if(method.getName().equals("setUserId")){
                System.out.println("======");
                Object invoke = method.invoke(o,1);
            }
        }
      System.out.println(o);
}

输出结果: User(userId=1, userName=null)

 

posted @ 2024-12-06 16:21  奋斗的渣渣  阅读(153)  评论(0)    收藏  举报