Reputation: 262
i'm stuck with Thrift about data types.
Now when i map and Integer value to a thrift generated bean, i'm using i32 type in the idl definition.
class MyBean {
Integer i = null;
}
struct TMyBean {
1: i32 i;
}
The problem is that in TMyBean generated bean, the i var is an int primitive type, than it's putting 0 as the default value, and for me 0 it's a valid value.
I've tried to put the optional keyword in the idl file, but things are not changing, it's always int.
How i've to handle this situation? i need i to accept a null value in TMyBean i var.
Thanks, Phaedra..
Upvotes: 3
Views: 4278
Reputation: 36001
Each generated java class (from a thrift struct) has methods to check if the primitives are set. It's more cumbersome than autoboxing but works.
Example: for a thrift struct TMyBean
that has a property myValue
, the following generated Java method would help to check if it's null:
isSetMyValue()
If you want to nullify the primitive, use:
setMyValueIsSet(false)
.
* I don't understand why Thrift decided not to use optional primitives as objects in Java and let autoboxing do it's magic. Perhaps because of large collections? Anyhow, sounds like another priority issue of preferring performance over simplicity.
Upvotes: 2
Reputation: 2764
Integer in java is a class, not a primitive. Thrift will only allow you to use defined primitives i16, i32, i64, double for numbers. i32 i
is equivalent to int i;
in Java; an int
always defaults to 0 in Java if it is not set. If you want to use a class, then you have to have a Thrift definition for that class that you can reference.
Upvotes: 1
Reputation: 13411
The optional
keyword was the right choice.
To test, whether or not a particular optional
field is set or not, use the isset
flags:
struct MyBean {
1: i32 IntValue
}
gives
public class MyBean implements org.apache.thrift.TBase<MyBean, MyBean._Fields>, java.io.Serializable, Cloneable, Comparable<MyBean> {
// ... lots of other code omitted ...
// isset id assignments
private static final int __INTVALUE_ISSET_ID = 0;
private byte __isset_bitfield = 0;
// ... lots of other code omitted ...
/** Returns true if field IntValue is set (has been assigned a value) and false otherwise */
public boolean isSetIntValue() {
return EncodingUtils.testBit(__isset_bitfield, __INTVALUE_ISSET_ID);
}
public void setIntValueIsSet(boolean value) {
__isset_bitfield = EncodingUtils.setBit(__isset_bitfield, __INTVALUE_ISSET_ID, value);
}
// ... even more code omitted ...
}
Upvotes: 2