我正在尝试创建一个方法,该方法使用对象的每个成员生成JobParameters对象。这是我到目前为止所得到的:
public static JobParameters getAttributesAsJobParameters(Object objectToConvert) throws IllegalAccessException {
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder();
for (Field field : objectToConvert.getClass().getDeclaredFields()) {
field.setAccessible(true);
jobParametersBuilder.addLong(field.getName(), (Long) field.get(objectToConvert));
}
return jobParametersBuilder.toJobParameters();
}
但是只有当对象没有任何与Long不同的成员时,这才有效。我怎样才能使其适用于所有原始类型?
答案 0 :(得分:1)
根据https://docs.oracle.com/javase/tutorial/reflect/member/fieldTypes.html,您可以使用field.getType()
来确定数据类型。
此处提供了Long
或long
(基元)类型字段的示例:Check type of primitive field
答案 1 :(得分:0)
感谢Eric给出的提示,我找到了一个可以解决更多问题的解决方案。对象:
public static JobParametersBuilder getAttributesAsJobParameters(Object objectToConvert) throws IllegalAccessException {
JobParametersBuilder jobParametersBuilder = new JobParametersBuilder().addLong("time", System.currentTimeMillis());
for (Field field : objectToConvert.getClass().getDeclaredFields()) {
field.setAccessible(true); // We need this to access to attributes if they are private
if (!field.getType().isPrimitive()) {
jobParametersBuilder = getAttributesAsJobParameters(field.get(objectToConvert));
} else {
matchJobParametersType(jobParametersBuilder, field, objectToConvert);
}
}
return jobParametersBuilder;
}
public static void matchJobParametersType(JobParametersBuilder jobParametersBuilder, Field fieldOfObject, Object object) throws IllegalAccessException {
String dataTypeOfField = fieldOfObject.getType().getSimpleName();
switch (dataTypeOfField) {
case "long":
jobParametersBuilder.addLong(fieldOfObject.getName(), (Long) fieldOfObject.get(object));
break;
case "String":
jobParametersBuilder.addString(fieldOfObject.getName(), (String) fieldOfObject.get(object));
break;
default:
throw new JobParametersException("Data type " + dataTypeOfField + " not defined");
}
}