Q. Why does the java sourcecode name match the same named class that has main method?
A. In Java, the name of the source code file must match the name of the public class defined within the file. This is a requirement for the Java compiler to compile the code correctly.
When we run a Java program, the JVM (Java Virtual Machine) looks for a public class with the name specified in the command line arguments. This class must have a main method with the following signature:
public static void main(String[] args)
If the JVM finds the specified class with the correct main method signature, it executes that method to start the program.
So, by convention, Java programmers name the class with the main method the same as the source code file to make it easier to locate the main class when running the program.
JVM(Java Virtual Machine)은 지정된 클래스의 메인 메소드를 호출하여 실행을 시작하고, main() 이후에 프로그램에 필요한 다른 모든 메서드를 호출합니다.
<Oralce JDK 7.0 중 메인메서드 구동원리 소스코드>
// 중간에 생략된 코드가 많습니다.
// main 메소드가 있는 클래스를 로딩한다.
mainClassName = GetMainClassName(env, jarfile);
mainClass = LoadClass(env, classname);
// main 메소드의 아이디를 찾는다.
mainID = (*env)->GetStaticMethodID(env, mainClass, "main", "([Ljava/lang/String;)V");
/*
mainClass, mainID를 가지고
java.lang.reflect.Method 객체로 변환한다.
JNI_TRUE면 static 메소드를 찾는다.
*/
jbject obj = (*env)->ToReflectedMethod(env, mainClass, mainID, JNI_TRUE);
/*
위에서 찾은 Method 객체를 이용하여
getModifiers라는 메소드의 아이디를 찾는다.
*/
mid = (*env)->GetMethodID(env, (*env)->GetObjectClass(env, obj), "getModifiers", "()I");
// getModifiers 메소드를 이용하여
// main 메소드의 접근지시자를 알아낸다.⭐⭐⭐
// public이 아니면 안된다!⭐⭐⭐
mods = (*env)->CallIntMethod(env, obj, mid);
if ((mods & 1) == 0) { /* if (!Modifier.isPublic(mods)) ... */
message = "Main method not public.";
messageDest = JNI_TRUE;
goto leave;
}
// String[] args를 가져온다.
mainArgs = NewPlatformStringArray(env, argv, argc);
// 드디어 실행시킨다!
(*env)->CallStaticVoidMethod(env, mainClass, mainID, mainArgs);