Search code examples
javaintellij-ideaimportthrift

How to import Thrift into Java program?


I’m writing a Java-programm for school that also uses Thrift. The problem is not so much the general programm/programm-logic itself, but just importing Thrift (to use it in a specific part).

My basic -possibly wrong- understanding is that you write the programm-code (here empfaenger.java), then you import Thrift into this file by adding the needed import-statements, e.g.:

import org.apache.thrift.TException;  
import org.apache.thrift.protocol.TBinaryProtocol;  
import org.apache.thrift.protocol.TProtocol;  
import org.apache.thrift.transport.TSocket ;  
import org.apache.thrift.transport.TTransport;  

and adding a file in the same directory from which they can actually can be imported, in this case libthrift-0.13.0.jar.(1) Then you later also import a compiled .thrift-file with the language-specific realization oft he IDL-code, that iself again imports some Thrift-classes. This file is here named syncautohersteller.

EDIT: The approach with the .jar-file was recommended by the prof.
Current project-structure (as seen in InteliJ):
enter image description here
The problem is now just that all the Thrift import-statements all throw errors, e.g.

  • empfaenger.java

java: package org.apache.thrift does not exist

  • syncautohersteller

package javax.annotation does not exist

so clearly i’m doing something wrong. Does anybody know how to fix this?


(1) I got the file from the Thrift folder (Home/Downloads/thrift-0.13.0/lib/java/build/libs and then the first of the three .jar-files in the folder) after installing Thrift using ./configure, sudo make and sudo make install and trying to verify by running “~/Downloads/thrift-0.13.0$ thrift –version” with result

Thrift version 0.13.0


Solution

  • In IntellJ Idea to add external Jars you can find some useful information in this question: Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project.


    I suggest you to manage the project's dependencies through Maven, which help you to add JAR dependencies to the classpath in a simpler way.
    First, you have to convert your project into a Maven project as explained in IntelliJ Idea documentation.
    Then you can follow these steps:

    1. Go to Maven repository website
    2. Search for Thrift
    3. Select first result
    4. Select the version you need enter image description here
    5. Copy the maven dependency

      org.apache.thrift libthrift 0.13.0

    6. Add maven dependency to your pom.xml file

    7. Execute a mvn clean install, after clicking the following button in IntelliJ enter image description here

      This process will help you and people which work with you to manage in a simpler way the dependencies of the project.