问题描述
实体类:public class Hotel {private long id;public long getId() {return id;}public void setId(long id) {this.id = id;}}测试方法:public void testReflect() throws Exception{Object object = Hotel.class.newInstance();String setMethod = "setId";Method method = object.getClass().getDeclaredMethod(setMethod, new Class[]{Object.class});method.invoke(object, new Object[]{1L});}出错信息:java.lang.NoSuchMethodException: setIdat java.lang.ClassCache.findMethodByName(ClassCache.java:247)at java.lang.Class.getDeclaredMethod(Class.java:731)at java.lang.reflect.Method.invokeNative(Native Method) 问题补充:abstruct 写道
解决方案
Method method = object.getClass().getDeclaredMethod(setMethod, new Class[]{long.class});
解决方案二:
亲,其实这样写就可以了!Method method = Hotel.class.getMethod("setId",long.class);
解决方案三:
public static void main(String[] args) throws Exception{Object o = Hotel.class.newInstance();String setMethod = "setId";Method[] methods = o.getClass().getMethods();for(int i=0;i<methods.length;i++){Method m = methods[i];//System.out.println(m.getName());if(m.getName().equals("setId")){System.out.println("1111");m.invoke(o, new Object[]{1L});}}//method.invoke(o, new Object[]{1L});}
解决方案四:
public void testReflect() throws Exception{ Object object = Hotel.class.newInstance(); String setMethod = "setId"; Method method = object.getClass().getMethod(setMethod); method.invoke(object, new Object[]{1L}); }