To simplify some bytecode analysis, I want to replace explicit (down)casts of primitive types in a Java program by calls to the equivalent method of the boxed type. In most cases it's simple:
double d = 42.0;
int i = (int)d;
Can be turned into
Double tmp = new Double(d);
int i = tmp.intValue();
This works for all signed types. But there is not such methods for char and Character. That is, Integer, Float, etc have the methods intValue, floatValue, etc. but none has a method charValue. Is there a jdk method to go from primitive type to char/Character?
So basically, is there something like this:
Integer num = new Integer(65);
char ch = num.charValue();
And the key is to not use (char).
If you're modifying bytecode, I think you do not need to cast to
char. In the bytecode, thechartype is a second-class citizen actually handled as anint. From JVMS §4.9.2:So while you can't, say, assign an
intto acharin the Java language without an explicit cast, you can do that in the bytecode, since they have the same "verification type", which isint. The bytecode representation of acharis just anintthat happens to have its upper two bytes zero. So instead of:You would be able to get away with (in bytecode):
And then just pretend that
chis achar(e.g., pass it to methods that expect acharor store it in acharfield or array).However, if I understand it correctly, that's what the
i2cinttocharcast instruction already does, so replacing it by an explicit AND operation is not going to be any simpler.When you cast from
floatordoubletobyte,short, orchar, it first casts toint, which saturates out-of-range values toInteger.MAX_VALUEorInteger.MIN_VALUE, and then truncates the bytes of theintto fit the final type. See JLS §5.1.3 – Narrowing Primitive Conversion. The truncation step means that conversion of out-of-range floating-point values tobyte,short, orcharis probably not going to give a useful result.