Skip to content

JavaParser LexicalPreservingPrinter fails when adding field using getType(0) #4898

@VKS1572

Description

@VKS1572

Problem

When using LexicalPreservingPrinter with JavaParser, calling:

cu.getType(0).addField(PrimitiveType.intType(), "foo");
Code to reproduce
var config = new ParserConfiguration();
config.setLexicalPreservationEnabled(true);

var cu = new JavaParser(config).parse("class Foo {\n" +
        "}").getResult().get();

LexicalPreservingPrinter.setup(cu);

cu.getType(0).addField(PrimitiveType.intType(), "foo");

System.out.println(LexicalPreservingPrinter.print(cu));

Expected behavior

It should add:

int foo;


inside the Foo class.

Actual behavior

The code fails because lexical preservation + string parsing does not produce a type accessible via getType(0).

Working fix
var clazz = cu.getClassByName("Foo").orElseThrow();
clazz.addField(PrimitiveType.intType(), "foo");

Environment

JavaParser version: (add here)

JDK version: (add here)

OS: (add here)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Need more inputIssue which need more discussion about the design/direction before implementing it fully.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions