Primitive Type Handling: getInt, getBoolean, and Type-Specific Methods
You'll learn how to use specialized Field methods that read and write primitive values directly, avoiding the performance overhead of boxing.
Why Type-Specific Methods Matter
When you use the generic Field.get() method on a primitive field (like int or boolean), Java must box the value into a wrapper object (Integer, Boolean, etc.). Similarly, Field.set() requires boxing the value before passing it in. This creates temporary objects and adds overhead.
The Reflection API provides type-specific methods like getInt(), getBoolean(), setDouble(), etc., that work directly with primitive values—no boxing required.
Type-Specific Getter Methods
Instead of get(), use these methods for direct primitive access:
getInt(Object obj)– reads anintfieldgetBoolean(Object obj)– reads abooleanfieldgetDouble(Object obj)– reads adoublefieldgetByte(),getShort(),getLong(),getFloat(),getChar()– for other primitives
These return the actual primitive type, not a boxed wrapper.
Type-Specific Setter Methods
Similarly, use these to write primitives directly:
setInt(Object obj, int value)setBoolean(Object obj, boolean value)setDouble(Object obj, double value)- And corresponding methods for other primitive types
Practical Example
Field scoreField = player.getClass().getDeclaredField("score");
scoreField.setAccessible(true);
// Efficient: direct primitive access, no boxing
int score = scoreField.getInt(player);
// Less efficient: boxing happens here
Integer boxedScore = (Integer) scoreField.get(player);
Analogy: It's like asking for water directly from the tap versus asking someone to pour it into a bottle first, then hand you the bottle. The direct approach is faster and simpler.
Key Takeaway:
Use type-specific methods like getInt() and setDouble() when working with primitive fields via reflection to avoid boxing overhead and improve performance.