Kotlin Foo::class.java "Unresolved Reference: Java" error - kotlin

I am trying to convert my Java code of HomePage.class to Kotlin. I am following the instructions on Kotlin.org:
getClass()
To retrieve the type information from an object, we use the javaClass
extension property.
val fooClass = foo.javaClass
Instead of Java’s Foo.class use
Foo::class.java.
val fooClass = Foo::class.java
I have a class called HomePage that extends AppCompatActivity (in Android). I am using Android Studio. I tried doing HomePage::class.java and it has an error: Unresolved reference: java
How do I get this to work?

The issue is most likely that you forgot to depend on the reflection libraries which were needed for the reflective functions of Kotlin.
On the Java platform, the runtime component required for using the
reflection features is distributed as a separate JAR file
(kotlin-reflect.jar). This is done to reduce the required size of the
runtime library for applications that do not use reflection features.
If you do use reflection, please make sure that the .jar file is added
to the classpath of your project.
Source

It turns out, I was using an older version of Kotlin, and it wasn't configured correctly. I edited the gradle file to include the latest beta version, and selected the option that configures Kotlin, and it works now.
In gradle:
buildscript {
ext.kotlin_version = '1.0.0-beta-3594'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
}
...
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}

I Put in the beginning of Gradle (Module app)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
and
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
or
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
in the dependencies section
In the build.gradle (Project)
buildscript {
ext.kotlin_version = '1.2.0'
repositories {
jcenter()
google()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

For easy reference, here are the reflection dependencies when using Gradle:
Reflection libraries from the docs for Gradle in your build.gradle
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
compile "org.jetbrains.kotlin:kotlin-reflect"
testCompile "org.jetbrains.kotlin:kotlin-test"
testCompile "org.jetbrains.kotlin:kotlin-test-junit"
}
Reflection libraries syntax for Kotlin Script Gradle DSL in your build.gradle.kts
dependencies {
compile(kotlin("stdlib"))
compile(kotlin("reflect"))
compile(kotlin("test"))
compile(kotlin("test-junit"))
}

In build.gradle (app) I had:
implementation 'androidx.core:core-ktx:1.6.0'
And I replaced it by
implementation 'androidx.core:core-ktx:1.5.0'
And it worked!
The core version also killed some of y functions like: forEach

I used
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
Instead of
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

i use this
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
invalided cache & restart android studio!works fine!!

This happened to me after updating Android Studio and the Kotlin plugin, which required migration to a newer version of Kotlin. After configuring everything correctly, the error still persisted. Deleting .idea folder and reloading did not help, but good old File -> Invalidate Caches / Restart did the trick for me.

I copied the class from other project and forgot to change the class package name.
when I changed, it fixed

I saw this in AndroidStudio with Kotlin 1.2.71 and none of the above fixed it for me.
What sadly hilariously worked for me was closing the project, telling AndroidStudio to forget about the project and re-opening from the folder. Presto, no unresolved reference. Weird, I know.

In my case reducing version of kotlin fixed the issue
Change
ext.kotlin_version = '1.3.21'
To
ext.kotlin_version = '1.3.11'

Add this line in your Module build gradle
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
In Project build gradle:
buildscript {
ext.kotlin_version = '1.3.21'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath 'com.google.gms:google-services:4.2.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

I encountered this error when i downloaded and run android studio canary(artic fox). Since then my android studio(normal one) was giving this error i applied all the solutions given above but nothing worked . So i completely uninstalled the android studio and reinstalled the latest one (this was the only option left)

Related

TornadoFX unresolved JavaFx

I wanted to create a new project that should be a desktop application. For this purpose, I have selected Kotlin language and TornadoFX framework. I have installed the TornadoFXplugin and created a new Ttornadofx-gradle-project. The base setup made by Intellij was successful but I have encountered a problem. When I wanted to run the generated project it failed. The project cannot resolve the java fx. I have dug through the web and found nothing that would fix the problem. The error log that I receive after the failed build is:
HAs anyone faces the same issue? How can I get rid of it?
I have installed the JDK 11 and set it up to the build config and I still receive the problem:
java.lang.UnsupportedClassVersionError: org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
Is there a change that I have missed something in the middle?
It looks like you are running the TornadoFX project with Java 11 or 12.
It also looks like the TornadoFX plugin is intended for Java 1.8, but it is not advised what to do with Java 11+.
Since Java 11, JavaFX is no longer part of the JDK.
You can read all about getting JavaFX as a third party dependency into your project here: https://openjfx.io/openjfx-docs/, and since you are using Gradle, this section will be helpful: https://openjfx.io/openjfx-docs/#gradle.
I've just installed the Tornado plugin, and created a project, using JDK 12.0.1. I've also updated the gradle-wrapper.properties file to use Gradle 5.3-bin as the default 4.4 doesn't work with Java 11+.
If I run it, I get the same errors:
e: /.../src/main/kotlin/com/example/demo/app/Styles.kt: (3, 8): \
Unresolved reference: javafx
e: /.../src/main/kotlin/com/example/demo/app/Styles.kt: (18, 13): \
Cannot access class 'javafx.scene.text.FontWeight'. Check your module classpath for missing or conflicting dependencies
...
Basically these errors indicate that JavaFX is not found. The Tornado plugin wasn't expecting this.
Solution
There is an easy solution to make this work: add the JavaFX gradle plugin to the build, so it deals with the JavaFX part.
According to the plugin's repository, all you need to do is edit the build.gradle file and add:
buildscript {
ext.kotlin_version = "1.2.60"
ext.tornadofx_version = "1.7.17"
ext.junit_version = "5.1.0"
repositories {
mavenLocal()
mavenCentral()
maven {
setUrl("https://plugins.gradle.org/m2/")
}
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.junit.platform:junit-platform-gradle-plugin:1.1.0"
// Add JavaFX plugin:
classpath 'org.openjfx:javafx-plugin:0.0.7'
}
}
apply plugin: "kotlin"
apply plugin: "application"
apply plugin: "org.junit.platform.gradle.plugin"
// Apply JavaFX plugin:
apply plugin: 'org.openjfx.javafxplugin'
// Add the JavaFX version and required modules:
javafx {
version = "12.0.1"
modules = [ 'javafx.controls', 'javafx.fxml' ]
}
...
And this is it, refresh your project, the IDE should recognize all the JavaFX classes.
If you modify the default MainView.kt like:
class MainView : View("Hello TornadoFX \n with JavaFX "
+ System.getProperty("javafx.version")) {
override val root = hbox {
label(title) {
addClass(Styles.heading)
}
}
}
you should be able to run it:
This answer is for those who wish to use Gradle Kotlin DSL.
An example of minimal build.gradle.kts:
plugins {
kotlin("jvm") version "1.4.0-rc"
application
id("org.openjfx.javafxplugin") version "0.0.9"
}
application { mainClassName = "com.example.MyApp" }
repositories {
mavenCentral()
jcenter()
maven("https://dl.bintray.com/kotlin/kotlin-eap")
}
dependencies {
// Kotlin standard library
implementation(kotlin("stdlib-jdk8"))
// TornadoFX dependency
implementation("no.tornado:tornadofx:1.7.20")
}
// JavaJX module to include
javafx { modules = listOf("javafx.controls", "javafx.fxml", "javafx.graphics") }
// Set Kotlin/JVM target versions
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
kotlinOptions.jvmTarget = "11" // or higher
kotlinOptions.languageVersion = "1.4"
}
// Be sure to use lates Gradle version
tasks.named<Wrapper>("wrapper") { gradleVersion = "6.6" }
For a full working example, check out GitHub repository
Please note that it also works with JDK 13 and 14
i'm recieved this error when download Kodein-Samples and trying to run tornadofx sample under Java11/12 and JavaFX13.
java.lang.UnsupportedClassVersionError: org/openjfx/gradle/JavaFXPlugin has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0
The solution was is quite simple: i'm only comment another modules in settings.gradle (because the error occurred in some other module). Unfortunately, after the launch the application generates an error when trying to edit the record. I haven't dealt with it yet.
so my build.gradle.kts looks like this:
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
val kodeinVersion: String by rootProject.extra
plugins {
kotlin("jvm")
application
id("org.openjfx.javafxplugin") version "0.0.8"
}
repositories {
jcenter()
maven(url = "https://dl.bintray.com/kodein-framework/Kodein-DI/")
}
application {
mainClassName = "org.kodein.samples.di.tornadofx.KodeinApplication"
}
javafx {
version = "13"
modules = mutableListOf("javafx.controls", "javafx.fxml", "javafx.base", "javafx.media")
}
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = JavaVersion.VERSION_11.toString()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("no.tornado:tornadofx:1.7.19")
implementation("org.kodein.di:kodein-di-generic-jvm:$kodeinVersion")
implementation("org.kodein.di:kodein-di-conf:$kodeinVersion")
implementation("org.kodein.di:kodein-di-framework-tornadofx-jvm:$kodeinVersion")
}
i made fork for this example with changes: https://github.com/ibelozor/Kodein-Samples

WARNING: API 'variant.getPackageLibrary()' is obsolete and has been replaced with 'variant.getPackageLibraryProvider()'

I just upadated kotlin to 1.3.30 and I now get this error when syncing gradle:
WARNING: API 'variant.getPackageLibrary()' is obsolete and has been
replaced with 'variant.getPackageLibraryProvider()'. It will be
removed at the end of 2019. For more information, see
https://d.android.com/r/tools/task-configuration-avoidance. To
determine what is calling variant.getPackageLibrary(), use
-Pandroid.debug.obsoleteApi=true on the command line to display a stack trace. Affected Modules: hydatabase
Here is my build.gradle:
apply plugin: 'com.squareup.sqldelight'
apply plugin: 'kotlin-multiplatform'
apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 19
}
lintOptions {
abortOnError false
}
}
sqldelight {
Database {
packageName = "com.company.hydatabase"
}
}
kotlin {
targets {
fromPreset(presets.jvm, 'jvm')
fromPreset(presets.android, 'android')
}
sourceSets {
commonMain.dependencies {
api 'org.jetbrains.kotlin:kotlin-stdlib-common'
}
jvmMain.dependencies {
api 'org.jetbrains.kotlin:kotlin-stdlib-jdk8'
// ICU4J: Use DecimalFormat
// Get rid of this when minSDKLevel = API 24 - Nougat (7.0)
// https://developer.android.com/guide/topics/resources/internationalization.html
api 'com.ibm.icu:icu4j:60.2'
}
androidMain.dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib'
api "com.squareup.sqldelight:android-driver:1.1.1"
}
androidMain.dependsOn jvmMain
}
}
task copyDatabase(type: Copy) {
from "${rootProject.file('hyappcommon/Databases/').path}"
into "${rootProject.file('hydatabase/src/main/assets/databases/').path}"
include '**/*.sqlite'
}
preBuild.dependsOn(copyDatabase)
// workaround for https://youtrack.jetbrains.com/issue/KT-27170
configurations {
compileClasspath
}
If you debug, it shows
REASON: The Kotlin plugin is currently calling this API. We are working to solve this.
To see this error please run
./gradlew -Pandroid.debug.obsoleteApi=true --stacktrace
As tommyboy said, the Kotlin plugin is calling this deprecated API.
If you don't want to get this warning while Kotlin is working on this, you can just use the previous version of Kotlin plugin like:
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.21"
}
It's probably a bug and fixed soon
You can revert back to the previous version or add this line to gradle.properties
android.debug.obsoleteApi=true
In my project gradle file I had
buildscript {
ext.kotlin_version = '1.3.31'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.3.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
Simple changing
ext.kotlin_version = '1.3.31' to ext.kotlin_version = '1.3.41' solved the problem
when using version 1.3.31 i had tried gradlew -Pandroid.debug.obsoleteApi=true
It mentioned
WARNING: API 'variant.getPackageLibrary()' is obsolete and has been
replaced with 'variant.getPackageLibraryProvider()'. It will be
removed at the end of 2019.
For more information, see https://d.android.com/r/tools/task-configuration-avoidance.
REASON: The Kotlin plugin is currently calling this API. We are working to solve this.
WARNING: Debugging obsolete API calls can take time during
configuration. It's recommended to not keep it on at all times.
Looks like it is solved in 1.3.41
It's an issue with the Kotlin plugin, as mentioned here. It'll get fixed in a later version.
After I updated Kotlin to 1.3.30, the following dependencies cause the error:
dependencies {
classpath 'com.jfrog.bintray.gradle:gradle-bintray-plugin:1.8.4'
classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1'
// ... other dependencies
}
I have reported the issue here:
https://github.com/bintray/gradle-bintray-plugin/issues/284
https://github.com/dcendents/android-maven-gradle-plugin/issues/81
By the way, you can ignore that error message.
The issue is tracked here and it is fixed.
Just use the Kotlin Gradle plugin v 1.3.40 or higher.
WARNING: API 'variant.getPackageLibrary()' is obsolete and has been replaced with 'variant.getPackageLibraryProvider()'.
It will be removed at the end of 2019.
Just updated to "v1.3.40-release-Studio3.4-1" plugin.
as you can see in https://youtrack.jetbrains.com/issue/KT-30784
I met this problem when I use kotlin plugin with library plugin. I found that if you use kotlin plugin with application plugin, it works well. But if you use kotlin plugin with library plugin, it will cause this problem. So that means:
// work well:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
// error:
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'
apply plugin: 'kotlin-android-extensions'
As the error diplayed that, you can use ./gradlew -Pandroid.debug.obsoleteApi=true --stacktrace to find out with module caused this problem.
Then I found that one of my module used the wrong plugin combination above. And that seems to be a bug of kotlin plugin. So finally, I upgraded the kotlin plugin, and then it worked well. Below is the kotlin plugin that I finally used:
buildscript {
ext.kotlin_version = '1.3.40'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
You can run this command in the root project
gradlew -Pandroid.debug.obsoleteApi=true
and the warning will be disappeared.

Unresolved references for Kotlin (JVM) Standard Library Elements

After adding gradle to an existing Kotlin project in IntelliJ, I started having issues with references to some standard library elements. For instance, Kotlin String type is recognized, but the mutableMapOf is giving me
Error:(11, 60) Kotlin: Unresolved reference: mutableMapOf
another is:
Error:(9, 78) Kotlin: Unresolved reference: Array
during compilation. They are marked red in the IDE, as well (not isolated to only compilation)
Another error that appears in IntelliJ is Kotlin not configured, with no options to configure Kotlin
Here is my gradle build file:
apply plugin: 'kotlin'
group = "com.serguei.myproject"
version = "1.0"
buildscript {
ext.kotlin_version = '1.2.10'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
}
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
compile 'com.google.code.gson:gson:2.8.2'
}
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
Thank you for the comments Ice100 and Preston Garno, they have helped greatly in finding a solution.
The issue was that my project was not structured correctly. I had:
MyProject -> src -> [Source Files]
-> build.gradle
however, after consulting Using Gradle more closely, it appears that the recommended project structure should be
MyProject -> src -> main -> kotlin -> [Source Files]
-> build.gradle
Once the project structure is adjusted, go into File -> Invalidate Caches / Restart and click the Invalidate and Restart. Once the indexer is rerun, the Kotlin standard library types, functions, etc. should now be available.
For any one coming to this page because of problem that IntelliJ suddenly does not find stuff in kotlin standard library: File -> Invalidate Caches / Restart helped me in a situation which didn't even involve gradle.
After migrating my Java app to Kotlin I find myself in this situation.
After checking gradle structure here
You can sync your project with gradle using sync button from menu bar.
this will download necessary files for Kotlin
Then you can just validate cache & Restart if necessary.

How to build my xtext language with gradle for android

I've written a test-DSL in xtext and generated an IntelliJ plugin.
I have a small Android-test project and in Android Studio my DSL-editor shows up and also generates the output files as expected.
Now I try to configure gradle to also generate the files, but this fails with an error.
I found the Android Integration section for the xtext-builder. This seems out-dated (e.g. it refers to org.xtext.android, which does not exist - also the link there is broken).
Anyway, in the xtext-gradle-plugin github repo there is an org.xtext.android.builder plugin: I guess this is the correct one.
My project build.gradle file looks like this (relevant parts only):
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/" // needed for org.xtext:xtext-android-gradle-plugin
}
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath "org.xtext:xtext-android-gradle-plugin:1.0.14"
}
}
allprojects {
repositories {
jcenter()
mavenLocal() // This is required so that the mydsl language is found
}
}
when I activate the org.xtext.android.builder plugin in the build.gradle file of in my app module:
apply plugin: 'com.android.application'
apply plugin: "org.xtext.android.builder" // causes the Error!
I get this error:
Error:Unable to find method 'com.android.build.gradle.api.BaseVariant.getJavaCompiler()Lorg/gradle/api/tasks/compile/AbstractCompile;'...
I guess there's some version mismatch or something is not up-to-date.
Any ideas?
This was a bug (#73) in the xtext-gradle-plugin. It was fixed in Version 1.0.16.

Why is Gradle not applying the dependency scope correctly under sourceSets in IntelliJ 2016?

I have a gradle project with a single module.
I have declared the 'provided' configuration to enable provided-scoped dependencies in the parent build.gradle file:
subprojects {
apply plugin: 'maven'
apply plugin: 'java'
apply plugin: 'idea'
configurations {
provided
}
idea {
module {
scopes.PROVIDED.plus += [configurations.provided]
}
}
sourceSets {
main.compileClasspath += configurations.provided
test.compileClasspath += configurations.provided
test.runtimeClasspath += configurations.provided
}
... other stuff...
}
In the module build.gradle I have declared the following dependencies:
dependencies {
testCompile 'org.elasticsearch:elasticsearch:2.3.1:tests'
compile 'org.apache.commons:commons-io:1.3.2'
compile 'org.apache.commons:commons-lang3:3.4'
compile 'org.elasticsearch:elasticsearch:2.3.1'
compile 'org.slf4j:slf4j-api:1.7.12'
provided 'org.slf4j:slf4j-simple:1.7.12'
}
When I expand the Gradle tool window, it declares the second to last dependency there as provided as well, even though it has compile scope:
I would expect to see the dependency listed with (Compile) next to it in this tool window, not (Provided).
So the question is: Why aren't I?
Is it because the implementation of slf4j (slf4j-simple) is provided, and depends on slf4j-api, so automatically makes that one provided as well? How do I stop that? Should I be stopping that? I want the API as a compiled dependency, but I want projects that use this to decide on their own implementation...
I had the very same problem with IntelliJ IDEA Ultimate build 163.12024.16. I wasn't able to fix it. BUT it magically disappeared when I upgraded to build 171.4249.39. (When using the previous build again, the scope goes back to the incorrect "provided" again.)