javaparser icon indicating copy to clipboard operation
javaparser copied to clipboard

Class which extends CompilationUnit loses license header

Open au-hao opened this issue 5 years ago • 2 comments

I'd like to extend CompilationUnit by adding a boolean field named isModified.

@Accessors(chain = true)
public class CustomCompilationUnit extends CompilationUnit {

    /**
     * Status indicates if this java file has been modified
     */
    @Getter
    @Setter
    private boolean isModified;

    public CustomCompilationUnit() {
        super();
    }

    public CustomCompilationUnit(CompilationUnit compilationUnit) {
        super(compilationUnit.getTokenRange().orElse(null),
                compilationUnit.getPackageDeclaration().orElse(null),
                compilationUnit.getImports(),
                compilationUnit.getTypes(),
                compilationUnit.getModule().orElse(null));
        
         compilationUnit.getStorage().ifPresent(storage -> setStorage(storage.getPath()));
    }

}
CompilationUnit parse = StaticJavaParser.parse(new File("test.java"));

CustomCompilationUnit customCompilationUnit = new CustomCompilationUnit(parse);        
System.out.println(customCompilationUnit);
System.out.println(customCompilationUnit.getTokenRange().get());

But when I try to invoke CustomCompliationUnit.toString, the final method in Node class, the String result doesn't include the license header in the file but TokenRange is correct.

I suspect that my way of initializing constructor here is wrong, but after debugging, still have no clue.

================================= Just manually set the comment there to make it work.

 compilationUnit.getComment().ifPresent(this::setComment);

au-hao avatar May 24 '19 17:05 au-hao

It's a general issue with how comment support has been created. It is a bug though, but one of many. The current situation is impossible to maintain.

So, this is waiting for someone to refactor comment support.

matozoid avatar May 27 '19 10:05 matozoid

As you are creating a new instance of CompilationUnit, you need to initialise the comments.

 compilationUnit.getComment().ifPresent(c-> setComment(c));

jlerbsc avatar Feb 08 '24 17:02 jlerbsc