-1

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

Developer
  • 1,713
  • 2
  • 14
  • 26
  • would you please more specific? – Rethinavel Dec 18 '13 at 07:56
  • null value cannot be detected at compilation time since the compilator cannot guess what input values would be. You can still test null values in your method and avoid the exception – slecorne Dec 18 '13 at 07:57
  • look into other way of achieving the same at http://stackoverflow.com/questions/997482/does-java-support-default-parameter-values. It is not exactly what you are asking for but it will give you a idea to implement the whole thing in different way. – Shaleen Dec 18 '13 at 08:01

2 Answers2

2

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.

Community
  • 1
  • 1
laalto
  • 137,703
  • 64
  • 254
  • 280
1

why don't just do:

if(o==null)
    o=default;
allemattio
  • 1,816
  • 14
  • 30