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, thechar
type is a second-class citizen actually handled as anint
. From JVMS §4.9.2:So while you can't, say, assign an
int
to achar
in 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 achar
is just anint
that 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
ch
is achar
(e.g., pass it to methods that expect achar
or store it in achar
field or array).However, if I understand it correctly, that's what the
i2c
int
tochar
cast instruction already does, so replacing it by an explicit AND operation is not going to be any simpler.When you cast from
float
ordouble
tobyte
,short
, orchar
, it first casts toint
, which saturates out-of-range values toInteger.MAX_VALUE
orInteger.MIN_VALUE
, and then truncates the bytes of theint
to 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
, orchar
is probably not going to give a useful result.