Java Reflection Flashcards

1
Q

What is reflection?

A
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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Why use reflection?

A

It is very powerful as it can break open objects and see their insides, even when guarded by JVM security manager.

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

What is the entry point for Reflection?

A

java.lang.Class

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

What are some Class instance methods?

A

getFields()
getField(String name)
getDeclaredFields()
getDeclaredField(String name)

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

Difference between getFields and getDeclaredFields?

A

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.

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

Difference between getConstructors and getDeclaredConstructors?

A

getConstructors returns all public constructors but getDeclaredConstructors returns all constructors.

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

What does getMethods do?

A

Returns an array of Method instances, containing details of all public methods associated with the class including inherited ones.

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

Why use Constructor.newInstance over Class.newInstance?

A

Constructor.newInstance can invoke any constructor irrespective of the number of parameters, not just no-argument constructors.
Constructor.newInstance can invoke privtae contructor.

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

How is access to the reflection API controlled?

A

via a security manager.

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

How do you override accessibility?

A
MyClass myClass = new MyClass();
Field theField = myClass.getClass().getDeclaredField("secretMessage");
theField.setAccessible(true);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are some common uses of reflection?

A

Test programs by forcing specific states
Insuring a high level of code coverage in a test suite
By debuggers to inspect running programs.

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