How do I set a Field to null using reflection in java?

654 Views Asked by At

This might seem like a stupid question at first, just do field.set(obj, null). But if the field is not an object, but a primitive, this will return an error. What I want is that it "resets" the value, no matter if it is an object, or a primitive (e.g. String -> null, int -> 0, boolean -> false). I have already tried doing field.getType().isPrimitive() ? 0 : null, hoping that the 0 would cast to short, byte, boolean, etc. automatically, but that did not work either. My current solution, a switch statement using field.getType(), is absolute garbage. Is there a cleaner, one-line solution to this?

0

There are 0 best solutions below