Reputation: 83
I've a service method in Java with following return type:
List<HashMap<String,Object>>
How can I best model it in thrift?
Upvotes: 4
Views: 4483
Reputation: 5668
AFAIK thrift does not directly support generic Object types which can be type casted to/from any object you like. You'll have to specifically define your object as in above example. You can't have a return type as Object. There's a work around mentioned here: Generic objects in Apache Thrift
Upvotes: 2
Reputation: 13411
Pretty straightforward:
struct MyObjectData {
// data of your objects
}
list< map< string, MyObjectData>>
You may want to make it a type:
typedef list< map< string, MyObjectData>> MyObjectStructure
The caveat lies in the data structure of MyObjectData
. If by Object
you literally mean any Object
, then we've got a problem. Thrift can't handle generic cases like this, because it does not support structures derived from each other (like you can do with class
). What you can do is, to use a union
holding different kinds of structs, where only one is used at a time:
struct Foo { /* some fields */ }
struct Bar { /* some fields */ }
// a union allows us to store different kinds of structs in one list
union Generic {
1: Foo foo
2: Bar bar
}
// technically, a union is more or less a struct with optional fields,
struct Alternative {
1: optional Foo foo
2: optional Bar bar
}
In case you need derived structures, I have solved this problem for me by doing this:
struct Base {
// some fields
}
struct Derived {
1: Base base_
// some more fields
}
which works quite well for me. If you have a deep inheritance tree, it might become somewhat painful to work with, but that's not the case in my particular case.
Upvotes: 6