测试反射的时候报错了代码如下
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)
标签:methods,invoke,cl,declaring,object,public,instance,method,out From: https://www.cnblogs.com/zjf6666/p/18591049