No, it's impossible because Java itself upgrades the char
to an int
if it can.
You could make an overload of your function that takes a char
parameter instead of an int
which might throw an exception, but that won't stop anyone from casting the char
to an int
and calling the int
version.
There is absolutely no difference at all between the character constant 'A'
cast to an integer and the integer 65, so it would be completely impossible to distinguish the cases.
Update from Pax:
I would argue that explicit casting is NOT passing a char
, it's the caller converting a char
to an int
then passing the int
. This solution catches the inadvertent passing of a char
.
Pinching someone's code from another answer, that would be:
public class Test {
private static void someMethod(char c) throws Exception {
throw new Exception("I don't think so, matey!");
}
private static void someMethod(int i) {
System.out.println(i);
}
public static void main(String[] args) throws Exception {
someMethod(100);
someMethod('d');
}
}
This results in:
100
Exception in thread "main" java.lang.Exception: I don't think so, matey!
at Test.someMethod(Test.java:4)
at Test.main(Test.java:13)