This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “Reflection API”.
1. What are the components of a marker interface? Answer: d 2. Which of the following is not a marker interface? Answer: d 3. What is not the advantage of Reflection? Answer: c 4. How private method can be called using reflection? Answer: b 5. How private field can be called using reflection? Answer: a 6. What is used to get class name in reflection? Answer: a 7. How method can be invoked on unknown object? Answer: c 8. How to get the class object of associated class using Reflection? Answer: a 9. What does Class.forName(“myreflection.Foo”).getInstance() return? Answer: d 10. What does foo.getClass().getMethod(“doSomething”, null) return? Answer: b
a) Fields and methods
b) No fields, only methods
c) Fields, no methods
d) No fields, No methods
Clarification: Marker interface in Java is an empty interface in Java.
a) Serializable
b) Cloneable
c) Remote
d) Reader
Clarification: Reader is not a marker interface. Serializable, Cloneable and Remote interfaces are marker interface.
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
Clarification: Reflection inspects classes, interfaces, fields and methods at a runtime.
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields
Clarification: getDeclaredMethods gives instance of java.lang.reflect.Method.
a) getDeclaredFields
b) getDeclaredMethods
c) getMethods
d) getFields
Clarification: getDeclaredFields gives instance of java.lang.reflect.Fields.
a) getClass().getName()
b) getClass().getFields()
c) getClass().getDeclaredFields()
d) new getClass()
Clarification: getClass().getName() is used to get a class name from object in reflection.
a) obj.getClass().getDeclaredMethod()
b) obj.getClass().getDeclaredField()
c) obj.getClass().getMethod()
d) obj.getClass().getObject()
Clarification: obj.getClass().getMethod is used to invoke a method on unknown object obj.
a) Class.forName(“className”)
b) Class.name(“className”)
c) className.getClass()
d) className.getClassName()
Clarification: forName(String className) returns the Class object associated with the class or interface with the given string name.
a) An array of Foo objects
b) class object of Foo
c) Calls the getInstance() method of Foo class
d) Foo object
Clarification: Class.forName(“myreflection.Foo”) returns the class object of Foo and getInstance() would return a new object.
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
Clarification: foo.getClass().getMethod() returns a method and we can call the method using method.invoke();