Coerced Access via Reflection

Java’s reflection features distinguish it from most other strongly typed, compiled languages. Java reflection allows deep introspection and manipulation of types at runtime. Used judiciously, this can lead to highly capable generic code in production systems, although care must be taken to avoid the inherent performance penalty. You can also commit great evils with the power of reflection.5 However, let’s use it for good: to increase our ability to test.

5. For some great examples of the evils that can be committed, see http://stackoverflow.com/questions/2481862/how-to-limit-setaccessible-to-only-legitimate-uses. My favorite part is making Strings mutable.

Consider a simple class with only a single private method, ...

Get Quality Code: Software Testing Principles, Practices, and Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.