您好我正在尝试使用反射来调用方法并更新该方法的setter值。但是我在使用该方法时遇到NoSuchMethodException。 我已经更新了代码。我很抱歉上一段代码中的错误。我已经重新编写了代码。当类的setMethod接受基本类型参数时会发生异常。
private static Object performMapping( Class voClass, Class[] clazz, Object voObject, Object data,String fieldType ){
voClass.getMethod( "set" + fieldType, clazz ).invoke( voObject, data );
return voObject;
}
private static Object mapField(ResultSet rs){
Class voClass=Class.forName( "com.test.Test" );
Object voObject = voClass.newInstance();
Class[] doubleArrayParamTypes = new Class[ 1 ];
doubleArrayParamTypes[ 0 ] = Double.class;
voObject = performMapping( voClass, doubleArrayParamTypes, voObject, rs.getDouble(fieldType.getColumn()), "Mark" );
}
/* This is my Class. I need to set the Mark. But it is primitive double. Is it possible to set the mark using the above code? */
public class Test{
private double mark;
public double getMark() {
return mark;
}
public void setMark(double mark) {
this.mark = mark;
答案 0 :(得分:1)
我看到的是,您传递setAddress1
并将其与set
连接,从而获得setsetAddress1
。传递属性名称并将其大写,或从连接中删除set
。
此外,您提供的代码将无法编译。您不能拥有名为class
答案 1 :(得分:0)
来自臀部的镜头,但你不是想要获得方法setsetAddress1
吗?
("set" + methodName
)
答案 2 :(得分:0)
以下代码有效。你有两个错误(除了语法类名错误):
package com.test;
import java.io.IOException;
import java.lang.reflect.*;
import java.util.Arrays;
public class Test {
Test() throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
SecurityException, InvocationTargetException, NoSuchMethodException {
}
private void m() throws IllegalArgumentException, SecurityException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException, InstantiationException {
Class[] doubleArrayParamTypes = new Class[1];
doubleArrayParamTypes[0] = Double.class;
Class clazz = Class.forName("com.test.Test");
Object voObject = clazz.newInstance();
Double data = 5.0;
performMapping(clazz, "Address1", doubleArrayParamTypes, voObject, data);
}
public static void main(String... args) throws IOException,
ClassNotFoundException, InstantiationException,
IllegalAccessException, IllegalArgumentException, SecurityException, InvocationTargetException, NoSuchMethodException {
new Test().m();
}
/* Reflection to set the data */
@SuppressWarnings("unchecked")
private void performMapping(Class clazz1, String methodName, Class[] clazz,
Object voObject, Double data)
throws IllegalArgumentException, SecurityException,
IllegalAccessException, InvocationTargetException,
NoSuchMethodException {
for (Method m : clazz1.getMethods()) {
System.out.println(m.getName()+ " " + Arrays.toString(m.getParameterTypes()));
}
clazz1.getMethod("set" + methodName, clazz).invoke(voObject, data);
}
public void setAddress1(Double arg) {
System.out.println(arg);
}
}
String
String data="TestData";
作为参数,即使您指定参数应为Double
类型:doubleArrayParamTypes[ 0 ] = Double.class;