Q&A : 자바 소스파일과 클래스파일명이 일치해야 하는 이유

NtoZ·2023년 3월 1일
0

Java

목록 보기
10/23
post-thumbnail

문제 상황

  • Java 연습문제 풀이 도중 main 메소드를 public 클래스가 아닌 다른 클래스에게 주고 동작을 실행했더니 Console 창에 아무런 결과값도 나타나지 않았다. 자바 소스파일과 public 클래스 이름이 같아야 한다는 것은 객체지향 파트에서 배워서 알고 있었지만, public 클래스가 main 메서드까지 포함해야 한다는 사실은 이해하기 어려웠다. JVM의 구동 원리와 연관이 있을 듯 했다.

Chat GPT

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.

  • 요약컨대, Java compiler가 코드를 올바르게 컴파일하기 위해서 소스코드와 동일한 public 클래스 이름을 가져야 하며, 그 public 클래스에 main 메서드를 배치해놓아야 한다.
    왜냐하면 우리가 자바를 실행할 때 JVM이 명령줄(command line) 인수에 지정된 이름을 가진 public 클래스를 찾기 때문이다.

Cross Chek

<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);

결론

  • JVM 이 구동될 때 main 메서드의 위치는 public이어야 하며, public은 소스코드 파일명과 일치해야 하므로,
    main 메서드의 위치는 public class 소스코드파일명에 존재해야함.
profile
9에서 0으로, 백엔드 개발블로그

0개의 댓글