Reflection Flashcards
What is the purpose of Java Reflection?
To enable programs to analyse themselves as well as other programs. Specifically, analysing fields, constructors
and methods of all accessors.
What is the entry point for the Reflection API?
The entry point of reflection is an immutable instance of the objects .class.
Why is Reflection costly?
Because it uses dynamic type checking as well as requires run time permissions.
Reflections breaks Java conventions. What might this result in?
Unexpected and unreliable output.
What are the 3 ways to obtain the class entry point for reflection?
- getInstace() called on the object.
- Access from the type E.g. float.class (works on reference and primitive types).
- forName() to get the class of the specified name.
What’s the difference between getFields() and getDeclaredFields()?
getFields() returns all public fields, including inherited ones.
getDeclaredFields() returns all fields (including private). Doesn’t include inherited fields.
What are the 2 main methods of creating new object instances in Reflection?
Constructor.newInstance() is used to call constructor of any accessor and argument type.
Class.newInstance() is used if constructor has no arguments and is public.
How can we modify private members using Reflection?
We have to temporarily modify the accessor of the member via setAccessible(true), and then we can
change the value. This is done in a try catch.
What are the 3 main uses of Reflection?
Force specific program states for testing.
Ensure a high level of code coverage.
Enable inspection of running programs for bugs.