Android not null values

2.2k views Asked by At

In Android, how can I prevent user to insert null values to my method. I don't want to fire an exception at run time. I want it to appear as compilation error

For example, if I have the following method

public void myMethod(Object o);

I don't want the user to be able to call it using

myMethod(null)

thanks in advance

2

There are 2 answers

0
allemattio On

why don't just do:

if(o==null)
    o=default;
0
laalto On

There are multiple notnull annotations such as IntelliJ's @NotNull that can help, e.g.

public void myMethod(@NotNull Object o)

However, if the contract of your method requires the param to be non-null, you could also write fail-fast defensive code and e.g. assert the contract:

public void myMethod(Object o) {
  Assert.assertNotNull(o);

where Assert is e.g. junit.framework.Assert included in Android runtime. The Java assert keyword is disabled in the VM by default.