Javaparser: Q:How to Modify Class Name without change the class code style?

Created on 6 Jun 2018  ·  1Comment  ·  Source: javaparser/javaparser

when i modify class name finish and save to a file , i find that the code style will be change , but i want to keep the same style with the file before .

i have more file have be modify ,and they maybe have different code style with each other, so i can not explicit defined compilationUnit.toString(prettyPrinterConfiguration) to get file content,.

so i want to only modify class name, have any easy way to do?

the code like that

    @Test
    public void test() throws IOException {
        File file = new File("c:/AppGroupController.java");
        byte[] bytes = FileCopyUtils.copyToByteArray(file);
        CompilationUnit compilationUnit = JavaParser.parse(new String(bytes, "utf-8"));
        compilationUnit.findAll(ClassOrInterfaceDeclaration.class).stream()
                .forEach(c -> {
                    String oldName = c.getNameAsString();
                    String newName = "Abstract" + oldName;
                    System.out.println("Renaming class " + oldName + " into " + newName);
                    c.setName(newName);
                });
        String newBody = compilationUnit.toString();
        FileCopyUtils.copy(newBody.getBytes("utf-8"), file);
    }
Question (JP usage)

Most helpful comment

Hello @xinluke, that because "toString" calls the pretty printer. Please take a look at the LexicalPreservingPrinter.

>All comments

Hello @xinluke, that because "toString" calls the pretty printer. Please take a look at the LexicalPreservingPrinter.

Was this page helpful?
0 / 5 - 0 ratings