Advanced 250+ TOP MCQs on Reflection API and Answers

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “Reflection API”.

1. What are the components of a marker interface?
a) Fields and methods
b) No fields, only methods
c) Fields, no methods
d) No fields, No methods

Answer: d
Clarification: Marker interface in Java is an empty interface in Java.

2. Which of the following is not a marker interface?
a) Serializable
b) Cloneable
c) Remote
d) Reader

Answer: d
Clarification: Reader is not a marker interface. Serializable, Cloneable and Remote interfaces are marker interface.

3. What is not the advantage of Reflection?
a) Examine a class’s field and method at runtime
b) Construct an object for a class at runtime
c) Examine a class’s field at compile time
d) Examine an object’s class at runtime

Answer: c
Clarification: Reflection inspects classes, interfaces, fields and methods at a runtime.

4. How private method can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: b
Clarification: getDeclaredMethods gives instance of java.lang.reflect.Method.

5. How private field can be called using reflection?
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields

Answer: a
Clarification: getDeclaredFields gives instance of java.lang.reflect.Fields.

6. What is used to get class name in reflection?
a) getClass().getName()
b) getClass().getFields()
c) getClass().getDeclaredFields()
d) new getClass()

Answer: a
Clarification: getClass().getName() is used to get a class name from object in reflection.

7. How method can be invoked on unknown object?
a) obj.getClass().getDeclaredMethod()
b) obj.getClass().getDeclaredField()
c) obj.getClass().getMethod()
d) obj.getClass().getObject()

Answer: c
Clarification: obj.getClass().getMethod is used to invoke a method on unknown object obj.

8. How to get the class object of associated class using Reflection?
a) Class.forName(“className”)
b) Class.name(“className”)
c) className.getClass()
d) className.getClassName()

Answer: a
Clarification: forName(String className) returns the Class object associated with the class or interface with the given string name.

9. What does Class.forName(“myreflection.Foo”).getInstance() return?
a) An array of Foo objects
b) class object of Foo
c) Calls the getInstance() method of Foo class
d) Foo object

Answer: d
Clarification: Class.forName(“myreflection.Foo”) returns the class object of Foo and getInstance() would return a new object.

10. What does foo.getClass().getMethod(“doSomething”, null) return?
a) doSomething method instance
b) Method is returned and we can call the method as method.invoke(foo,null);
c) Class object
d) Exception is thrown

Answer: b
Clarification: foo.getClass().getMethod() returns a method and we can call the method using method.invoke();

Leave a Reply

Your email address will not be published. Required fields are marked *