Jake Trent

Expose Fields via Java Reflection

For unit testing purposes, I often want to set field values in objects so that I can setup for the test conditions. One of most annoying things about testing is the urge to change code design for just the sake of testing – especially if it’s in a way that is considered less safe, like exposing elements or lessening accessibility. (This is not to say that trying to test code can reveal certain code smells and prompt refactoring). I, myself, have a number of setter methods with this comment prepended: “// for test only comments”. Stinkers! Well, sometimes enough becomes enough. So, here’s a way to set any field on an object w/o exposing it. This is done via reflection.

Read more

Java Reflection for methods with primitive params

First-class objects are the norm in the code that I usually write and edit, but every now and then I run across a method with a primitive parameter. I use EasyMock a lot in testing, and need to find these methods by reflection, this is how it’s done…

Read more

Use Java Reflection to Get Field w/ Accessor

Java is about objects. Reflection is about knowing things about those objects generally without have specific fields and methods in hand. I must get to one of those field values via its accessor, allowing me to keep the fields private and abstracted away… of course, until I start unit testing. Here’s one method…

Read more