For example, if you are developing a command line tool, you may want to test or debug the main
method. Reflection is useful in such cases, but how can the main
method be executed from reflection? The conclusion is the sample below.
try {
Method mainMethod = Sample.class.getMethod("main", String[].class);
String[] args = {"arg1", "arg2", "arg3"};
mainMethod.invoke(null, (Object) args);
} catch (NoSuchMethodException
| SecurityException
| IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
Is it ʻinvokeas a point? __ Give
null to the first argument, and specify ʻargs
cast to ʻObjectfor the subsequent variable-length argument part. __ Let's protect these two points and have fun reflecting (´ ・ ω ・
)
Recommended Posts