Reflection API in Java Flashcards
What is meant by reflection?
Reflection is the ability for a class or object to examine itself.
What is the reflection API?
The reflection API is an interface used to write Java code to look at the class of an object and determine its structure.
The ability to break open objects is typically guarded by the…
Security manager
What is the standard rule for reflection?
Another object shouldn’t be able to use the reflection API to do something it couldn’t do without ordinary compiled Java code.
What is the entry point for the reflection API?
The immutable java.lang.Class object generated for each class by the JVM at runtime.
If you don’t know the type name, how would you get the Class object of a class?
You can use object.getClass(), which is inherited by all classes and returns this instance’s class’s class object.
If you do know the type name, how would you get the Class object of a class?
You can simply use the .class keyword.
e.g. MainClass.class
If, for some reason, you have a string with a reference to the class namespace, how could you get the Class object of a class?
You can use Class.forName(String str), where str is your string class reference.
What is the difference between getFields and getField?
getFields eturns an array of all Field instances, detailing all public attributes associated with the class, including inherited ones.
getField returns only one Field, which is the one specified by the String argument.
What is the difference between getFields and getDeclaredFields?
HINT: What does Declared mean in this case?
getFields returns Field object(s) for attributes associated with the class, even inherited ones.
getDeclaredFields does the same, but not including inherited ones.
Declared, in this case, means Fields declared within the class.
What is the difference between getConstructors and getDeclaredConstructors?
HINT: Different from getFields
getConstructors returns public constructors associated with that class, while getDeclaredConstructors returns all constructors associated with that class.
What does getMethods do?
getMethods returns an array of Method instances, containing details of all public methods associated with this class, including inherited ones.
What does the parameterised definition of getMethods do?
When parameters are given, getMethods returns only one method, relating to the specified public method, which may be inherited, whose name matches the String name and whose arguments match the types in …argumentTypes.
Will getDeclaredFields return inherited Fields?
No.
Will getDeclaredConstructors return inherited Constructors?
No. You cannot inherit constructors, so this mode instead returns all constructors regardless of access level.