-
a single file (Constants.java) containing all constant definitions
-
one file per struct, enum and service
$ tree gen-java `-- thrift `-- example |-- Constants.java |-- Location.java |-- Tweet.java |-- TweetSearchResult.java |-- TweetType.java `-- Twitter.java
Tip
|
Naming Conventions
While the Thrift compiler does not enforce any naming conventions, it is advisable to stick to standard naming conventions otherwise you may be in for some surprises. For instance, if you have a struct named tweetSearchResults (note the mixedCase), the Thrift compiler will generated a Java file named TweetSearchResults (note the CamelCase) containing a class named tweetSearchResults (like the original struct). This will obviously not compile under Java. |
Thrift maps the various base and container types to Java types as follows:
-
bool: boolean
-
binary: byte[]
-
byte: byte
-
i16: short
-
i32: int
-
i64: long
-
double: double
-
string: String
-
list<t1>: List<t1>
-
set<t1>: Set<t1>
-
map<t1,t2>: Map<t1, t2>
As you can see, the mapping is straight forward and one-to-one for the most part. This is not surprising given that Java was the primary target language when the Thrift project began.
The Java language does not have any native support for "typedefs". So when the Thrit Java code generator encounters a typedef declaration, it merely substitutes it with the original type. That is, even though you may have typedefd TypeA to TypeB, in the generated Java code, all references to TypeB will be replaced by TypeA.
Consider the example IDL above. The declaration for tweets in the generated code for TweetSearchResults is simply public List<Tweets> tweets.
Thrift enums map to Java enum types. You can obtain the numeric value of an enum by using the getValue method (via the interface TEnum). In addition, the compiler generates a findByValue method to obtain the enum corresponding to a numeric value. This is more robust than using the ordinal feature of Java enums.
Thrift puts all defined constants in a public class named Constants as public static final members. Constants of any of the primitive types are supported.
Tip
|
Contain your Constants
If you have multiple Thrift files (in the same namespace) containing const definitions, the Thrift compiler will overwrite the Constants.java file with the definitions found in the file processed last. You must either define all your constants in a single file, or invoke the compiler on a single file that includes all the other files. |