|
| 1 | +# Write to a Field |
| 2 | + |
| 3 | +Similarly, you can write to a field using the `.set` method on a `Field` object. |
| 4 | +This will also throw `IllegalAccessException` if its not something you are allowed to do. |
| 5 | + |
| 6 | +```java |
| 7 | +import java.lang.reflect.Field; |
| 8 | + |
| 9 | +class Main { |
| 10 | + void main() throws IllegalAccessException { |
| 11 | + Class<Drink> drinkClass = Drink.class; |
| 12 | + |
| 13 | + Field caffeinatedField; |
| 14 | + try { |
| 15 | + caffeinatedField = drinkClass.getField("caffeinated"); |
| 16 | + } catch (NoSuchFieldException e) { |
| 17 | + throw new RuntimeException(e); |
| 18 | + } |
| 19 | + |
| 20 | + var water = new Drink("Water", false); |
| 21 | + |
| 22 | + // You can put drugs in anything you set your mind to, kids |
| 23 | + caffeinatedField.set(water, true); |
| 24 | + |
| 25 | + System.out.println(caffeinatedField.get(water)); |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +class Drink { |
| 30 | + public String name; |
| 31 | + public boolean caffeinated; |
| 32 | + |
| 33 | + Drink(String name, boolean caffeinated) { |
| 34 | + this.name = name; |
| 35 | + this.caffeinated = caffeinated; |
| 36 | + } |
| 37 | +} |
| 38 | +``` |
| 39 | + |
| 40 | +If you try to set a field to the wrong type of value - like setting a `boolean` field to have a `String` value - |
| 41 | +you will get an `IllegalArgumentException`. Unlike `NoSuchFieldException` and `IllegalAccessException` this is an |
| 42 | +unchecked exception, so you do not need to explicitly account for it. |
| 43 | + |
| 44 | +```java |
| 45 | +import java.lang.reflect.Field; |
| 46 | + |
| 47 | +class Main { |
| 48 | + void main() throws IllegalAccessException { |
| 49 | + Class<Drink> drinkClass = Drink.class; |
| 50 | + |
| 51 | + Field caffeinatedField; |
| 52 | + try { |
| 53 | + caffeinatedField = drinkClass.getField("caffeinated"); |
| 54 | + } catch (NoSuchFieldException e) { |
| 55 | + throw new RuntimeException(e); |
| 56 | + } |
| 57 | + |
| 58 | + var soda = new Drink("Soda", true); |
| 59 | + |
| 60 | + caffeinatedField.set(soda, "yes, very much so"); |
| 61 | + |
| 62 | + System.out.println(caffeinatedField.get(soda)); |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +class Drink { |
| 67 | + public String name; |
| 68 | + public boolean caffeinated; |
| 69 | + |
| 70 | + Drink(String name, boolean caffeinated) { |
| 71 | + this.name = name; |
| 72 | + this.caffeinated = caffeinated; |
| 73 | + } |
| 74 | +} |
| 75 | +``` |
0 commit comments