ECM2414 Reflection Flashcards

1
Q

What is reflection in Java?

A

Reflection is the ability of a class or object to examine itself, allowing Java code to inspect and manipulate fields, methods, and constructors dynamically.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Where are the classes supporting reflection located?

A

In the java.lang.reflect package.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the standard rule regarding the use of reflection?

A

Reflection should not allow access to private fields or methods unless explicitly permitted by the JVM security manager.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you obtain a Class instance in Java?

A

Using getClass() on an object instance: object.getClass()
Using .class for a type: String.class
Using Class.forName(“fully.qualified.ClassName”).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the difference between getFields() and getDeclaredFields()?

A

getFields(): Returns all public fields, including inherited ones.
getDeclaredFields(): Returns all fields declared in the class, regardless of access modifiers, excluding inherited fields.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do getConstructors() and getDeclaredConstructors() differ?

A

getConstructors(): Returns only public constructors.
getDeclaredConstructors(): Returns all constructors, regardless of access modifiers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the limitations of Class.newInstance() compared to Constructor.newInstance()?

A

Class.newInstance() only calls no-argument constructors and requires visibility.
Constructor.newInstance() can invoke any constructor, including private ones, under certain conditions.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What does setAccessible(true) do in reflection?

A

It overrides normal accessibility checks, allowing access to private fields, methods, or constructors, depending on the JVM’s security policy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Why is reflection slower than non-reflective code?

A

Reflection bypasses compile-time checks, preventing some JVM optimizations and resulting in slower performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What are common uses of reflection?

A

Debuggers to inspect running programs.
Test programs by forcing specific states.
Ensuring high code coverage in test suites.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the risks associated with using reflection?

A

Potential security vulnerabilities.
Side effects leading to dysfunctional code.
Breaking abstractions, reducing portability, and potentially changing behavior with platform upgrades.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly