Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

What is the purpose of the following code? Explain how it works. typesMatch is a

ID: 671435 • Letter: W

Question

What is the purpose of the following code? Explain how it works. typesMatch is a method that returns a Boolean if the types in the first parameter match the types in the second parameter.

public static Object whatDoIDo (String name, Object[] args)

{

try{

Class<?> givenClass = Class.forName(name);

Constructor<?>[] givenConstructors = givenClass.getConstructors();

for(int i = 0; i < givenConstructors.length; i++)

if(typesMatch(givenConstructors[i].getParameterTypes(), args)

return givenConstructors[i].newInstance(args);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (InstantiationException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (IllegalArgumentException e) {

e.printStackTrace();

} catch (InvocationTargetException e) {

e.printStackTrace();

}

return null;

}

Explanation / Answer

Here, we are trying to instantiate an object of a class passed as parameter with its the constructor by passing the parameter arguments.

1. if class is not found of the given name, then we get "class not found" exception

2. after that if it cannpt be instantiated , then we get "instatiation" exception

3. 3rd exception is when the constructors cannot be accessed

4. 4th exception is when the arguments passed doesnot match with the parameters of the given constructor

5. if there is a failure in invocation of the target object

if no exception is found then either we have returned the object created or default "null" object

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote