JAVA/Java Study

자바 동적 컴파일

늑인 2023. 9. 18. 10:43

해당 방법은 자바 컴파일러(javac)를 사용하여 클래스 파일을 생성한 예제이다.

 

 

1. 프로세스를 통한 자바에서 컴파일러 호출 메서드 부분. 

 public String execute(String command) {
        StringBuffer output = new StringBuffer();
        Process process = null;
        BufferedReader bufferReader = null;
        Runtime runtime = Runtime.getRuntime();
        String osName = System.getProperty("os.name");

        // 윈도우일 경우
        if (osName.indexOf("Windows") > -1) {
            command = "cmd /c " + command;
        }

        try {
            process = runtime.exec(command);
            Scanner s = new Scanner(process.getInputStream(), "euc-kr");
            while (s.hasNextLine() == true) {
                //표준출력으로 출력
                output.append(s.nextLine() + System.getProperty("line.separator"));
            }
            s = new Scanner(process.getErrorStream(), "euc-kr");
            while (s.hasNextLine() == true) {
                // 에러 출력
                output.append(s.nextLine() + System.getProperty("line.separator"));
            }
        } catch (IOException e) {
            output.append("IOException : " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                process.destroy();
                if (bufferReader != null) bufferReader.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
//        System.out.println("this end");
        return output.toString();
    }

 

2. 클래스 이름과, 클래스 내용을 메소드에 담아서 보냄.

    public String compile(String clsName, String clsStr) {
        // 클래스 이름과, 자바 파일 내용 포함.
        // 자바 파일 생성.
        File file = wirteClass(clsName, clsStr);
        
        //자바 파일 컴파일 명령어 
        String command = "javac -encoding UTF-8 dynamic/" + clsName + ".java";
        String result = execute(command);
        // 임시 생성된 자바 파일 삭제.
        file.delete();
        return result;
    }
    
    public File wirteClass(String clsName, String stringClass) {
        String folder = System.getProperty("user.dir") + "\\dynamic";
        // 임의의 패키지명 부여
        return write(folder, clsName + ".java", "package dynamic; " + stringClass);
    }

    private File write(String folderName, String fileName, String result) {
        File folder = new File(folderName);
        if (!folder.exists()) folder.mkdirs();
        FileWriter fw;
        try {
            File file = new File(folderName, fileName);
            fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(result);
            bw.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

다음 글에서 동적 컴파일 된 클래스를 호출하는 예제를 확인해 보겠다.