简单的测试一下反射应用,结果出乎意料
public static void main(String[] args) {
Gjr1 gjr = new Gjr1(2);
System.out.println(gjr.getClass().getCanonicalName());
try {
Method mt = gjr.getClass().getMethod("sum", Integer.class, Double.class);
System.out.println(mt.invoke(gjr, 1, 1.44));
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class Gjr1 {
int in;
public Gjr1(int i) {
this.in=i;
}
public double sum(int i,double m) {
return in+i+m;
}
}
按理说是应该直接执行但是
这是什么情况,经过几番尝试,改为Method mt = gjr.getClass().getMethod("sum", int.class, double.class);
终于
慎记,基本类型的class对象与其包装类的class对象不是等价的,用于反射时必须与传参强一致