好吧,我有这个方法,我不确定如何处理它的一部分,它是评论以感叹号开头的地方:“// !!!!这是我关心的部分......”
public Person getPersonFromRS(ResultSet rs) throws SQLException, NoSuchMethodException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
Person person = new Person();
// getting the fiels and methods of the class Person
Field[] fields = person.getClass().getDeclaredFields();
Method[] methods = Person.class.getClass().getDeclaredMethods();
String setter = "set";
// just ignoring these fields of the class
for (Field field : fields) {
if (field.getName().equals("nul") || field.getName().equals("pairMarriages")
|| field.getName().equals("pairMarriage_Date") || field.getName().equals("pairBiography")) {
continue;
}
// getting the value from resultSet as string
String value = "";
try {
value = rs.getString(field.getName());
} catch (Exception e) {
System.err.println("Error with getting the column " + field.getName() + " from database");
continue;
}
// if value is not null and the string inside not NULL, set the value to the person
if (!(value == null))
System.out.println("THE RETRIEVED VALUE: " + value);
if ((!(value == null)) && !value.equals(nul)) {
// methodName = setParameter
String methodName = setter + field.getName();
System.out.println("\nmethod Name: " + methodName);
Method method = null;
try {
System.out.println("The field type is " + field.getType());
method = person.getClass().getDeclaredMethod(methodName, field.getType());
} catch (Exception e) {
System.err.println(e);
continue;
}
// !!!! this is the part that concerns me, what's the best way to handle this part in order
// to avoid this flood for every type?
// determining the type of the value to set in
Type type = field.getType();
if (field.getType() == String.class) {
method.invoke(person, value);
} else if (field.getType() == long.class) {
method.invoke(person, Long.parseLong(value));
} else if (field.getType() == int.class) {
method.invoke(person, Integer.parseInt(value));
} else if (field.getType() == PersonDate.class) {
PersonDate date = new PersonDate(value);
method.invoke(person, date);
}
}
}
return person;
}
有没有一种最佳的方法来做到这一点,而不是像这样处理每一个参数类型?我的意思是这对我来说似乎是开销?