nivekastoreth
nivekastoreth

Reputation: 1427

"Incompatible types" error while compiling runtime parameter annotation using static import

Using the following annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface Param {
    String value();
}

And constants class:

public final class ExampleConstants {
    public static final String classConstant  = "classConstant";
    public static final String methodConstant = "methodConstant";
    public static final String paramConstant  = "paramConstant";
}

The following class:

import com.example.annotations.Control;
import com.example.annotations.Param;
import com.example.annotations.Task;

import static com.example.ExampleConstants.*;

@Task(value = classConstant)
public class ExampleClass {
    @Control(methodConstant)
    public Object control(@Param(paramConstant) ExampleParam paramConstant) {
        return null;
    }
}

Fails to compile with the error:

Error:(12, 34) java: incompatible types
  required: java.lang.String
  found:    com.example.ExampleParam

If I change the @Param annotation declaration to not use the static import, it compiles as expected:

public Object control(@Param(ExampleConstants.paramConstant) ExampleResult paramConstant)

I'm looking for clarification on the following:

Upvotes: 1

Views: 1247

Answers (1)

kapex
kapex

Reputation: 29969

There is no limitation that annotation values can't have static and/or wildcard imports.

The error indicates that the value is of the type ExampleParam - The issue here is that the method's parameter has the same name as the imported constant: paramConstant

In the example with the ExampleConstants.paramConstant the value is more specific and therefore isn't hidden any more.

Rename the parameter, so it doesn't hide the imported value any more:

public Object control(@Param(paramConstant) ExampleParam exampleParam)

Upvotes: 2

Related Questions