Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can type safety be guarded against implicit conversion in Java?

Tags:

java

Suppose a method is as following:

void foo(int i)
{
}

Is there a way to make the following call illegal or generate an exception?

foo((short)3);
like image 469
Hong Avatar asked Dec 04 '22 12:12

Hong


2 Answers

Maybe this?

class AClass {
  void foo(int x) { /* do work */ }
  void foo(short x) { throw new IllegalArgumentException(); }
}
like image 94
Bruno Reis Avatar answered Feb 09 '23 01:02

Bruno Reis


Bruno's overloading will work, but if you are looking at preventing other types of casting, you can always box the integer into its Object class:

void foo(Integer i) {
    // handle data normally
}

This will prevent you from being able to send short arguments to it.

like image 41
Farlan Avatar answered Feb 09 '23 00:02

Farlan