square / javapoet

A Java API for generating .java source files.
Apache License 2.0
10.82k stars 1.37k forks source link

Request static-imports on a CodeBlock #421

Open ronshapiro opened 8 years ago

ronshapiro commented 8 years ago

It would be nice to be able to request a member to be statically imported when it's being added to a CodeBlock instead of assuming it will be and then later on in the JavaFile remembering to request it.

For example, in:

CodeBlock statement = 
    CodeBlock.builder().add("$T.checkNotNull($L)", Preconditions.class, reference)
        .requestStaticImport(Preconditions.class, "checkNotNull")
        .build();

If I end up adding this to a MethodSpec, then great, the JavaFile which includes it is aware of it. If multiple conflicting signatures request a static import, then JavaFile can disambiguate. in the same way it does for imports. If I never end up including it, then I don't end up emitting an unused import.

This might require a new identifier, maybe $M for a MemberSelect:

CodeBlock statement = 
    CodeBlock.builder().add(
        "$M($L)",
        MemberSelect.of(Preconditions.class, "checkNotNull", ImportPolicy.STATIC)
    .build();
sormuras commented 8 years ago

Your $M proposal reminds me of #317 and #388 in particular. (-:

swankjesse commented 8 years ago

As a workaround, you could keep a collection of the static imports you want, and build that collection while you’re building the code blocks.

ronshapiro commented 8 years ago

Another benefit of requesting static imports at the CodeBlock level is that when they are finally wrapped up into a JavaFile, you can verify that no other methods in that file conflict. If they do, then JavaPoet can ignore the request to static import, otherwise it can choose to qualify.

sormuras commented 8 years ago

If I never end up including it, then I don't end up emitting an unused import.

I'll modify #412 to skip unused imports.