I'd like to perform a safety check for my getClass().getField(...).set(...)
where the value I am setting should match the type of that field, (int x = 1 should only allow Integers to be set). The problem is, I'm having a hard time finding ways to compare the two. Currently this is the code:
int foo = 14;
Field field = getClass().getDeclaredField("foo");
Object source = this;
// make the field accessible...
public void safeSet(Object newValue) throws IllegalAccessException {
// compare the field.getType() to the newValue type
field.set(source, newValue);
}
I've tried a lot of things, and searched around the web for quite a bit, but cannot find an answer which solely focuses on this usage of it. I've tried things like field.getType().getClass().equals(newValue.getClass())
, field.getType().equals(newValue)
, and more, and they do not work. How can I reasonably compare a primitive field.getType() to an Object value passed in, or, how would I, in this case, compare an int
, to an Integer
?
Aucun commentaire:
Enregistrer un commentaire