|
Hi:
Sorry for my late reply.
It is possible to invoke a method and providing null as one of the parameters by also providing the parameter (arguments) types together with the parameter values. The ReflectionUtil class provided with this article requires the following changes:
public static Method getDeclaredMethod(Object object, String name,
Class>?<... paramTypes) throws NoSuchMethodException {
Method method = null;
Class>?< clazz = object.getClass();
do {
try {
method = clazz.getDeclaredMethod(name, paramTypes);
} catch (Exception e) {
}
} while (method == null & (clazz = clazz.getSuperclass()) != null);
if (method == null) {
throw new NoSuchMethodException();
}
return method;
}
public static Object invokeMethod(Object object, String methodName,
Class>?<[] paramTypes, Object[] parameters)
throws NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
Method method = getDeclaredMethod(object, methodName, paramTypes);
method.setAccessible(true);
return method.invoke(object, parameters);
}
You can invoke a method, say setName(String) from the Product class, and provide null as argument as shown below:
String name = null;
Object[] param = { name };
Class>?<[] paramTypes = { String.class };
ReflectionUtil.invokeMethod(product, "setName", paramTypes, param);
System.out.println(product.getName());
Hope this helps.
<br/>
Albert Attard
|