&#34; <标识符>预期&#34;从模板</identifier>创建类时

时间:2014-09-25 18:06:22

标签: java

我有一个我正在创建的机器人,它可以从IRC通道获取输入,以便为运行时使用的机器人创建新类。但是,当它尝试编译该类时,会在类名称中导致“标识符预期”错误。但是,如果我输入的类与使用模板的机器人创建的类相同,则编译时没有问题。以下是此过程使用的3种方法:

//Create basic command
public static int writeBasicCommand(String trigger, String output, boolean edit) {
    int success = 0, existenceError = 1, unknownError = 2;
    try {
        String filePath = "C:/commands/" + trigger + ".java"; //Location for new class
        File file = new File(filePath);

        //Check if command exists
        if (file.exists()) {
            if(!edit) {
                return existenceError;
            }
        } else if(edit) {
            return existenceError;
        }

        //Grab and modify template
        String template = readFile("C:/template.txt");
        String namedCom = template.replace("--COMMANDNAME--", trigger);
        String content = namedCom.replace("--COMMANDRESULT--", "\"" + output + "\"");

        //Write command
        WriteFile(content, file, false);
        if (Compile(filePath)==true) {
            System.out.println("Done");
            return success;
        } else {
            return unknownError;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return unknownError;
    }
}

//Compile new commands
public static boolean Compile(String fileToCompile) {
    System.setProperty("java.home", "C:\\Program Files\\Java\\jdk1.7.0_11");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int compilationResult = compiler.run(null, null, null, fileToCompile);
    if(compilationResult == 0) {
        System.out.println("Compilation is successful");
        return true;
    } else {
        System.out.println("Compilation Failed");
        if ((new File(fileToCompile).exists())) {
            new File(fileToCompile).delete();
        }
        return false;
    }
}

//Write to a file
public static boolean WriteFile(String fileContents, File destination, boolean append) {
    try {

        // if file doesnt exist, then create it
        if (!destination.exists()) {
            destination.createNewFile();
        }

        FileWriter fw = new FileWriter(destination.getAbsoluteFile(), append);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(fileContents);
        bw.close();
        fw.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

0 个答案:

没有答案