通过JAVA反射调用方法的问题,一个很简单的示例,就给出有疑问的地方了

2024-12-26 13:42:35
推荐回答(3个)
回答1:

StudentTester t= (StudentTester )addMethod.invoke(studentTester, new Integer(100),new Integer(200)); 考虑到你问的问题,我在想你的这个方法的返回值是StudentTester的类型吗?
=================================以下是我写的一个利用反射方法进行数据保存的例子你可以参考下
protected int save(String setObjectMethodName,Class entityclassname,Collection col){
int f = 0;
Method method;
try {
String tablename = HibernateConfigurationHelper.getTableName(entityclassname);
method = CommonBiz.class.getDeclaredMethod("save",Class.class,String.class,Class.class,List.class);
f = (Integer)method.invoke(CommonBiz.class.newInstance(),new Object[]{this.getClass(),setObjectMethodName,entityclassname,(List)col});
} catch (Exception e) {
e.printStackTrace();
return -1;
}
return 0;
}

回答2:

只能强制转换。那方法返回的就是Object

Object invoke(Object obj, Object... args)
Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.

回答3:

int result = (int)addMethod.invoke(studentTester, new Integer(100),new Integer(200));
你像上面这么写的?
如果是,改为:
Integer result = (Integer)addMethod.invoke(studentTester, new Integer(100),new Integer(200));
int不是Object的子类