简体   繁体   中英

How to use JAR in code? Easy at Android Studio but it doesn't work in IntelliJ IDEA

In Android Studio I've created a dummy project to testing package Klaxon , that handles JSON . So I put the below code inside onCreate do change the text of creatorButton button.

class Product(val name: String)  // Kotlin, but could be Java
val product = Product("HDD")
val result = Klaxon().toJsonString(product)   
creatorButton.text = result 

Klaxon is in jcenter repository. So in Build.Gradle module file, I've added in dependency group:

implementation 'com.beust:klaxon:5.0.1'

When I've run the app in my Android cell phone, the button display the label

{"Name":"HDD"}

After, I want to test Klaxon in depth on IntelliJ IDEA so I don't need emulate or run in cell phone all the times that I want to test something.

So I've created a empty Kotlin project with Gradle .

fun main() {
    class Product(val name: String)
    val product = Product("HDD")
    val result = Klaxon().toJsonString(product)  // Error
    println(result)
}

I follow the tips in this question and add the JAR library in Project Structure (It doesn't work) or add the JAR library in libs folder and run "Add as Library"(it did not work either)

PS: I've tried to edit the dependencies in Gradle.build , but it not accept the same Android Studio syntax.

How can I do to solve this mistery? No matter what I do, it always gives error on the line with Klaxon call()

I discovered a different trick, since no attempt to edit Gradle in IntelliJ IDEA using sames commands as I do in Android Studio has worked inside dependencies group: I try to use implementation with a jcenter string, with files or filetree command (as explained in documentation )

First, I've closed the Kotlin project with Gradle .

Then I've created a new Kotlin project without include Gradle (it's the most important step), copy all source code and add the JAR file in the same way proposed in stackoverflow question.

So I check if in File / Settings/ Editor / General / Auto Import , the option Insert Import on Paste is all , and Add unambiguous import on the fly is on .

Finally when I use the function Klaxon() , Intellij IDEA asks about the missing import and I've confirmed with Alt+Enter .

And the source code receives the line

import com.beust.klaxon.Klaxon

Now my Kotlin code works as a charm

By the way, if one sees the External Library in the project tree (left side), one child node is klaxon.5.0.5.jar that is my library. It derives to com.beust.klaxon the open to the class names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM