Flat Buffers - Table



Overview

The very basic building block of Flat Buffers is the table attribute. This is equivalent to a class in the languages that we use, for example, Java, Python, etc.

Example Code

Following is the syntax that we need to have to instruct Flat Buffers that we will be creating instances of a given table −

namespace com.tutorialspoint.theater;

table Theater {
}
root_type Theater;

We will save the above in "theater.fbs" and we will use this when we explore other data structures.

Explanation

namespace com.tutorialspoint.theater;

This argument is specific to Java, i.e., the package where the code from the ".fbs" file will be auto-generated. The class Theater will be created in com.tutorialpoint.theater package.

Next, we're creating a table, Theater −

table Theater

This is nothing but the class name of the base class for the object which would be created/recreated. Note that it is useless in its current shape, as it does not have any other attributes. But we will be more adding attributes as we move along.

Using multiple table attributes

A single fbs file can also have multiple tables. For example, if we want, we can add a Visitor table as well in the same file. Flat Buffers would ensure that Theater class remains main class using root_type attribute. For example −

namespace com.tutorialspoint.theater;

table Theater {
}

table Visitor {
}
root_type Theater;

Creating Java Classes from fbs file

To use Flat Buffers, we will now have to use flatc binary to create the required classes from this ".fbs" file. Let us see how to do that −

flatc --java theater.fbs

Using Java Classes created from a fbs file

Well, that is it! The above command should create the required files in the current directory and now we can use them in our Java code −

// Create a FlatBuffer Builder with default buffer
FlatBufferBuilder builder = new FlatBufferBuilder(1024);

// Create Theater FlatBuffers using startTheater() method
Theater.startTheater(builder);

At this stage, it is not very useful, as we have not added any attributes to the table. Let us do that when we look at strings in Flat Buffers - string chapter.

Advertisements