1
1
package org .code .javabuilder .util ;
2
2
3
3
import java .lang .reflect .Method ;
4
+ import java .lang .reflect .Modifier ;
4
5
import java .net .URLClassLoader ;
5
6
import java .util .List ;
6
7
import org .code .javabuilder .JavaProjectFile ;
@@ -18,8 +19,8 @@ private ProjectLoadUtils() {
18
19
* @param classLoader class loader pointing to location of compiled classes
19
20
* @param javaFiles a list of JavaProjectFiles
20
21
* @return the main method if it is found
21
- * @throws UserInitiatedException if there is more than one main method or no main method, or if
22
- * the class definition is empty
22
+ * @throws UserInitiatedException if there is more than one main method, no main method, an error
23
+ * with the main method signature, or if the class definition is empty
23
24
*/
24
25
public static Method findMainMethod (URLClassLoader classLoader , List <JavaProjectFile > javaFiles )
25
26
throws UserInitiatedException {
@@ -28,10 +29,7 @@ public static Method findMainMethod(URLClassLoader classLoader, List<JavaProject
28
29
try {
29
30
Method [] declaredMethods = classLoader .loadClass (file .getClassName ()).getDeclaredMethods ();
30
31
for (Method method : declaredMethods ) {
31
- Class [] parameterTypes = method .getParameterTypes ();
32
- if (method .getName ().equals ("main" )
33
- && parameterTypes .length == 1
34
- && parameterTypes [0 ].equals (String [].class )) {
32
+ if (method .getName ().equals ("main" )) {
35
33
if (mainMethod != null ) {
36
34
throw new UserInitiatedException (UserInitiatedExceptionKey .TWO_MAIN_METHODS );
37
35
}
@@ -46,6 +44,20 @@ public static Method findMainMethod(URLClassLoader classLoader, List<JavaProject
46
44
}
47
45
}
48
46
47
+ // If we found a main method, make sure the method signature is valid
48
+ // (public, static, void return type, one argument which should be a String[]).
49
+ if (mainMethod != null ) {
50
+ final Class <?>[] parameterTypes = mainMethod .getParameterTypes ();
51
+ final int modifiers = mainMethod .getModifiers ();
52
+ if (!Modifier .isPublic (modifiers )
53
+ || !Modifier .isStatic (modifiers )
54
+ || mainMethod .getGenericReturnType () != Void .TYPE
55
+ || parameterTypes .length != 1
56
+ || !parameterTypes [0 ].equals (String [].class )) {
57
+ throw new UserInitiatedException (UserInitiatedExceptionKey .INVALID_MAIN_METHOD );
58
+ }
59
+ }
60
+
49
61
return mainMethod ;
50
62
}
51
63
0 commit comments