0

I'm using Lombok (I have the plugin installed and I also restarted the IDE), however I'm getting a strange error. Here's my code:

@RequiredArgsConstructor
@Slf4j
@Service
@Profile("parser")
public class ParserExecutorService implements CommandLineRunner {

    @Value("${input.directory}")
    String inputDirectory;

    @Override
    public void run(String... args) throws Exception {
        getLogFiles();
    }

    public void getLogFiles() {

        File inputDirectory = new File(inputDirectory);

The last line throws an error:

Value 'inputDirectory' might not have been initialized

However, when I provide there a normal String, i.e.:

File inputDirectory = new File("c:/temp");

and I print the "inputDirectory" below that, then it is visible with a proper value in the console.

So, why on Earth it throws this error while using this property?

I tried setting it to

private final String inputDirectory;

but it didn't help either.

randomuser1
  • 2,733
  • 6
  • 32
  • 68
  • Don't mind that the linked question reports a NullPointerException, the cause is the same as in your question and the answers explain why (and provide a solution). – Tom Dec 27 '20 at 17:31

1 Answers1

4

This has nothing to do with lombok whatsoever.

File inputDirectory = new File(inputDirectory);

That line is an error no matter how you slice it. The inputDirectory in new File(inputDirectory) is a reference to the very inputDirectory variable you have declared on this line. Which, obviously, is not initialised yet.

hence, lombok is unrelated to this.

The fix? Easy - use another name, because this is confusing. Alternatively: File inputDirectory = new File(this.inputDirectory); - disambiguate, make sure javac understands that the second usage of inputDirectory is referring to the field, whereas the first is referring to 'please make me a new local variable named inputDirectory that shadows the field also named inputDirectory'.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72