September 2019
Intermediate to advanced
816 pages
18h 47m
English
Without nest-based access control, reflection capabilities are also limited. For example, before JDK 11, the following snippet of code would throw IllegalAccessException:
Car newCar = new Car();Engine engine = newCar.new Engine();Field powerField = Engine.class.getDeclaredField("power");powerField.set(engine, power);
We can allow access by explicitly calling powerField.setAccessible(true):
...Field powerField = Engine.class.getDeclaredField("power");powerField.setAccessible(true);powerField.set(engine, power);...
Starting with JDK 11, there is no need to call setAccessible().
Moreover, JDK 11 comes with three methods that enrich the Java Reflection API with support for nests. These methods are Class.getNestHost() ...