My lack of Java is biting me on the heels again. I have the following member function:
protected void setData(Map<String, String[]> data) {
Class thisClass = this.getClass();
for(Map.Entry<String, String[]> item : data.entrySet()) {
try {
Field field = thisClass.getDeclaredField(item.getKey());
try {
if(field.getType().getName().equals("java.lang.Long")) {
// EXCEPTION HERE!!!
field.setLong(this, Long.valueOf(item.getValue()[0]) );
}...
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} catch (NoSuchFieldException e) {
// Skip this field...
continue;
}
}
}
I keep on getting an IllegalArgumentException, and i don’t fully understand why. Can anyone offer some insight?
The function takes a map, which it iterates, and assigns the values to “this” by checking if the field exists on “this” and if so, attempts to call field.set().
setLong(..)tries to set a primitive value, and your fields isjava.lang.Long. Always use theset(..)method for non-primitives. For primitivesgetType().getName()would returnint,long, etc.Initial answer: You need to make the field accessible:
field.setAccessible(true)