Java Reflection Flashcards
What is reflection?
Reflection is the ability for a class or an object to examine itself. Allows java code to look at the class of an object and determine its structure.
Why use reflection?
It is very powerful as it can break open objects and see their insides, even when guarded by JVM security manager.
What is the entry point for Reflection?
java.lang.Class
What are some Class instance methods?
getFields()
getField(String name)
getDeclaredFields()
getDeclaredField(String name)
Difference between getFields and getDeclaredFields?
getFields returns a field relating to public attributes associated with the class, including inherited ones, but getDeclaredFields returns an array of Field instances, containing details of all variables regardless of their access modifiers, not including inherited ones.
Difference between getConstructors and getDeclaredConstructors?
getConstructors returns all public constructors but getDeclaredConstructors returns all constructors.
What does getMethods do?
Returns an array of Method instances, containing details of all public methods associated with the class including inherited ones.
Why use Constructor.newInstance over Class.newInstance?
Constructor.newInstance can invoke any constructor irrespective of the number of parameters, not just no-argument constructors.
Constructor.newInstance can invoke privtae contructor.
How is access to the reflection API controlled?
via a security manager.
How do you override accessibility?
MyClass myClass = new MyClass(); Field theField = myClass.getClass().getDeclaredField("secretMessage"); theField.setAccessible(true);
What are some common uses of reflection?
Test programs by forcing specific states
Insuring a high level of code coverage in a test suite
By debuggers to inspect running programs.