5

I have two methods that in some cases have ambiguous call. For example:

void bla(Integer a);
void bla(String a);

Basically when I call bla(null) I will get ambiguous call error. Is it possible to write or use some annotation that will solve this issue before the compiler phase?

Can I block a null option from in bla(String a) before the compiler kicks in? I tried to wrote a NotNull annotation (but it kicks in after the compile phase).

See code below:

@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER, ElementType.LOCAL_VARIABLE})
public @interface NotNull1 {
    String value() default "";
}

void bla(@NotNull1 String a);
Avi Levin
  • 1,868
  • 23
  • 32

1 Answers1

8

Cast null to the type of the parameter of the method.

bla((Integer) null);
bla((String) null);
SOFe
  • 7,867
  • 4
  • 33
  • 61
  • 2
    Yes I know that solution :) Since I'm writing an SDK I have no control on the casting phase. I would like to disable the possibility of entering a null to the void bla(String a) method without the user getting ambiguous error in the process. – Avi Levin Jan 31 '16 at 10:18
  • Could you show an example of what you are doing? I don't know how this can happen without you explicitly calling it with `null`. – SOFe Jan 31 '16 at 10:22
  • Yes, I wrote an example in the main question. – Avi Levin Jan 31 '16 at 10:30
  • I meant you how called it. – SOFe Jan 31 '16 at 10:36
  • My project is available inside a JAR file so I test features in another java project by importing the JAR. – Avi Levin Jan 31 '16 at 10:39
  • Yes, but I meant the syntax how you call this method. I don't see how you can create that error without explicitly doing `bla(null)`. – SOFe Jan 31 '16 at 10:41
  • I'm doing it in my test project. :) I added a new method with the same name and tested what will happen if i will call a method with null. – Avi Levin Jan 31 '16 at 10:45