ECM2414 Reflection Flashcards
What is reflection in Java?
Reflection is the ability of a class or object to examine itself, allowing Java code to inspect and manipulate fields, methods, and constructors dynamically.
Where are the classes supporting reflection located?
In the java.lang.reflect package.
What is the standard rule regarding the use of reflection?
Reflection should not allow access to private fields or methods unless explicitly permitted by the JVM security manager.
How can you obtain a Class instance in Java?
Using getClass() on an object instance: object.getClass()
Using .class for a type: String.class
Using Class.forName(“fully.qualified.ClassName”).
What is the difference between getFields() and getDeclaredFields()?
getFields(): Returns all public fields, including inherited ones.
getDeclaredFields(): Returns all fields declared in the class, regardless of access modifiers, excluding inherited fields.
How do getConstructors() and getDeclaredConstructors() differ?
getConstructors(): Returns only public constructors.
getDeclaredConstructors(): Returns all constructors, regardless of access modifiers.
What are the limitations of Class.newInstance() compared to Constructor.newInstance()?
Class.newInstance() only calls no-argument constructors and requires visibility.
Constructor.newInstance() can invoke any constructor, including private ones, under certain conditions.
What does setAccessible(true) do in reflection?
It overrides normal accessibility checks, allowing access to private fields, methods, or constructors, depending on the JVM’s security policy.
Why is reflection slower than non-reflective code?
Reflection bypasses compile-time checks, preventing some JVM optimizations and resulting in slower performance.
What are common uses of reflection?
Debuggers to inspect running programs.
Test programs by forcing specific states.
Ensuring high code coverage in test suites.
What are the risks associated with using reflection?
Potential security vulnerabilities.
Side effects leading to dysfunctional code.
Breaking abstractions, reducing portability, and potentially changing behavior with platform upgrades.