How to protect security from implicit conversion in Java?

Assume the method is as follows:

void foo(int i) { } 

Is there a way to make the next call illegal or throw an exception?

 foo((short)3); 
+4
source share
3 answers

Bruno overloading will work, but if you want to prevent other types of castings, you can always insert an integer in your Object class:

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

This will prevent the possibility of sending short arguments.

+4
source

Maybe this?

 class AClass { void foo(int x) { /* do work */ } void foo(short x) { throw new IllegalArgumentException(); } } 
+9
source

This solution may not be what you are looking for, but I would use the overload function to create one version of void foo(int) that processes the data as normal, and another version with the signature void foo(short) that processes the data, such like a mistake. For instance:

 void foo(int i) { // handle data normally } void foo(short s) { throw new IllegalArgumentException("your message here"); } 
+3
source

Source: https://habr.com/ru/post/1469336/


All Articles