Error incompatible types nonexistentclass cannot be converted to annotation

I'm using Dagger 2 and Kotlin for Android development. My project is also a multi-module project. My settings.gradle file is like this: include :app include :lib I'm also maintaining the lib modu...

I’m using Dagger 2 and Kotlin for Android development.
My project is also a multi-module project.
My settings.gradle file is like this:

include :app
include :lib

I’m also maintaining the lib module.

In the Dagger Files (for example in the component), I try to get the item from other module. For example:

@Component
interface AppComponent{
    fun getPresenter() : Presenter
}

The Presenter object is defined in lib module. I was working in linux environment and I’m using Android Studio 3 preview canary 5. The code is working well and I am able to generate APK.

But my company wanted to generate the APK using stable version of Android Studio. I’m using Android Studio 2.3.3.

When compiling the Android Project, I encountered this error:

error: error.NonExistentClass

The error appears when

:app:kaptDebugKotlin 

is performed and caused by the dagger class cannot found, the class is defined in the other project. What can be the possible workaround for this? Sorry for my bad English.

Full code is in https://github.com/jimisdrpc/demo-grpc-jaeger

This question was originally posted in https://stackoverflow.com/questions/65207682/kotlin-grpc-error-incompatible-types-nonexistentclass-cannot-be-converted-to.

I am getting the error mentioned above using this build.gradle

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.4.10"
    id("org.jetbrains.kotlin.kapt") version "1.4.10"
    id("org.jetbrains.kotlin.plugin.allopen") version "1.4.10"
    id("com.github.johnrengelman.shadow") version "6.1.0"
    id("io.micronaut.application") version "1.2.0"
    id("com.google.protobuf") version "0.8.13"
}

version = "0.1"
group = "com.tolearn"

repositories {
    mavenCentral()
    jcenter()
}

micronaut {
    testRuntime("junit5")
    processing {
        incremental(true)
        annotations("com.tolearn.*")
    }
}

//https://stackoverflow.com/a/55646891/4148175
//kapt {
//    correctErrorTypes true
//}

dependencies {

    //implementation("io.grpc:protoc-gen-grpc-kotlin:1.0.0")

    implementation("io.micronaut:micronaut-validation")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
    implementation("io.micronaut:micronaut-runtime")
    implementation("io.micronaut.grpc:micronaut-grpc-runtime")
    implementation("javax.annotation:javax.annotation-api")
    implementation("io.micronaut:micronaut-http-client")
    implementation("io.micronaut:micronaut-tracing")

    runtimeOnly("io.jaegertracing:jaeger-thrift")
    runtimeOnly("ch.qos.logback:logback-classic")
    runtimeOnly("com.fasterxml.jackson.module:jackson-module-kotlin")
}


application {
    mainClass.set("com.tolearn.ApplicationKt")
}

java {
    sourceCompatibility = JavaVersion.toVersion("11")
}

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
        dependsOn ':generateProto'
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }


}

sourceSets {
    main {
        java {
            srcDirs("build/generated/source/proto/main/grpc")
            srcDirs 'build/generated/source/proto/main/grpckt'
            srcDirs("build/generated/source/proto/main/java")
        }
    }
}

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:3.14.0" }
    plugins {
        grpc { artifact = "io.grpc:protoc-gen-grpc-java:1.33.1" }
        grpckt { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.0.0:jdk7@jar"}
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
            grpckt {}
        }
    }
}

And here is the proto file

syntax = "proto3";

option java_multiple_files = true;
option java_package = "com.tolearn";
option java_outer_classname = "DemoGrpcJaeger";
option objc_class_prefix = "HLW";

package com.tolearn;

service DemoGrpcJaegerService {
  rpc send (DemoGrpcJaegerRequest) returns (DemoGrpcJaegerReply) {}
}

message DemoGrpcJaegerRequest {
  string name = 1;
}

message DemoGrpcJaegerReply {
  string message = 1;
}

When I run «gradle clean build» it points an error on autogenerated DemoGrpcJaegerServiceGrpcKt.java complaining in @error.NonExistentClass()

Содержание

  1. kapt replaces generated class references with error.NonExistentClass despite kapt.correctErrorTypes being enabled
  2. NonExistentClass cannot be converted to Annotation
  3. 5 Answers 5
  4. ERROR : error.NonExistentClass Kotlin In multi module Dagger project
  5. 18 Answers 18
  6. The Root Cause
  7. How to fix it (the workaround)
  8. My Case:
  9. NonExistentClass не может быть преобразован в аннотацию
  10. ОШИБКА: error.NonExistentClass Kotlin В многомодульном проекте Dagger
  11. 14 ответов
  12. Коренная причина
  13. Как это исправить (обходной путь)
  14. Мое дело:

kapt replaces generated class references with error.NonExistentClass despite kapt.correctErrorTypes being enabled

I have a custom annotation processor that does roughly this:

  • generate an annotation type (classes using this type are deferred until later rounds)
  • in a later round, process the classes using this type and generate some more files for them

This has worked well so far in Java. But recently, I’ve been converting some of my classes from Java to Kotlin. The setup is still the same. But when I converted a class using the generated annotation type to Kotlin, this error popped up:

error: incompatible types: NonExistentClass cannot be converted to Annotation @error.NonExistentClass()

It’s worth noting that this only happens when the file is in Kotlin — other (Java) files also use the same annotation, and they don’t produce an error when I remove the annotation from the Kotlin file.

After some googling, I found out that the recommended solution is to add an option to the build.gradle :

However, using this did not fix the problem. I looked at the generated stub file, and it’s clear that kapt keeps putting error.NonExistentClass in there despite the setting:

I think it’s worth noting that:

  • the stub kept the correct import for the generated annotation
  • kapt moved the annotation to a static method, while the original generated annotation supports only fields

MyClass looks like this:

And here’s the build.gradle :

There have been other people with this problem on SO, but none of the solutions suggested there have fixed it for me.

Источник

NonExistentClass cannot be converted to Annotation

I added a new Retrofit interface to my project containing a couple of Endpoints annotated with the @GET and @HEADERS annotations, after Injecting said interface to a repository class using the @Inject annotation in the constructor of said class, Android Studio throws this error:

After taking a look at the generated Java code, it replaces the @GET and @HEADERS annotations with this:

I’ve already tried the following:

Using annotatioProcessor instead of kapt

Setting jetifier.enabled to false in gradle.properties

Setting generateStubs to true in my build.gradle file

Setting correctErrorTypes to true in my build.gradle file

Android Studio 3.3

could it be some dagger scope issue? or Retrofit / dagger not fully compatible with the new versions of the Kapt plugin?

5 Answers 5

Luckily this question led me to figure out my issue. While moving around classes from an app module into a library, I was referencing an annotation class which only existed in a debug folder. So debug builds were fine, but calls to gradlew install failed when generating release files.

The error for me was very explicit although it took me a long time to realize — the generated file had literally replaced the missing annotation with @error.NonExistentClass()

Moving the file into the main src set meant both debug and release builds could see the class. What took me a while to figure out was that I assumed this was a Dagger issue being masked by kapt, but really it was just a regular old Dagger issue. My advice is to look at your Dagger setup carefully.

Источник

ERROR : error.NonExistentClass Kotlin In multi module Dagger project

I’m using Dagger 2 and Kotlin for Android development. My project is also a multi-module project. My settings.gradle file is like this:

I’m also maintaining the lib module.

In the Dagger Files (for example in the component), I try to get the item from other module. For example:

The Presenter object is defined in lib module. I was working in linux environment and I’m using Android Studio 3 preview canary 5. The code is working well and I am able to generate APK.

But my company wanted to generate the APK using stable version of Android Studio. I’m using Android Studio 2.3.3.

When compiling the Android Project, I encountered this error:

The error appears when

is performed and caused by the dagger class cannot found, the class is defined in the other project. What can be the possible workaround for this? Sorry for my bad English.

18 Answers 18

Just add this to build gradle file to avoid the issues related NonExistentClass

The Root Cause

Basically, there’s not much that can be done to fix this when using kapt . To quote this link that tackles the same problem in another library that uses pre-processors (OrmaDatabase):

Because Kotlin makes its stubs before Java Annotation Processing runs, Kotlin knows just nothing about OrmaDatabase, and the name of the declaration in stubs will be error.NonExistentClass. This breaks the Annotation Processing tool. It’s a kind of kapt limitation

How to fix it (the workaround)

Just use plain apt or annotationProcessor for running Dagger compiler. As soon as I changed:

in my module level build.gradle file, I was able to get the errors. After you’ve fixed the errors, you gotta revert the line back to kapt because otherwise dagger classes wouldn’t be generated since they’re defined in Kotlin.

I had a very similar situation with a NonExistentClass error in a multi-module project using Dagger and turns out I forgot to add the kotlin library dependency. So, just adding it in the sub-module solved my problem:

tldr: Change kapt to annotationProcessor in build.gradle and you will see the real problem.

I got the same error, and it turned out that I just commented out a class that I was using in my AppComponent. Unfortunately the kapt tool didn’t give me the proper error message. If you change the kapt to annotationProcessor at your library’s compiler, and try to build, it won’t succeed neither, but you will get a more detailed error message.

In my case, I had @Nullable annotation from support-annotations while I had removed it in order to migrate to AndroidX .
When building, because the annotation was not imported correctly, it was detected as invalid.

What I did was to check the code and fix all imports.

After removing the outdated library

I got this error:

I’ve found if you’re using

changing to false will then present the actual error, you will probably have issues building the Dagger Graph once it’s compilation issues have been corrected, but simply change back to true, and you should be good

It seems, there is a bug with kapt, project cleaning should help.

I got this error when I had moved by mistake a test class into my main sourceset. Moving it back to the test sourceset got rid of the error.

I received this error, when there was a compilation error in my Injected class. Please ensure that there aren’t any compilation errors.

For all those arriving like me on this topic with a similar error.
Check your annotation imports.
For me the problem was I had the @MicronautTest annotation same as another test just the wrong one. Somehow intellij seems to think the import is fine while it really is not.

I had
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
yet needed the kotest one.
import io.micronaut.test.extensions.kotest.annotation.MicronautTest

The kapt error is, while technically correct, quite uninformative. So just check the imports and if they are all correct.

This means there is a problem with providing dependencies( and not the dependency itself!).

Sometimes annotation processor(in this case Dagger) is unable to build dependency graph on the first build iteration due to a provider absence.

For instance: You are passing GlideApp as a parameter in your provider while GlideApp class is not generated yet! So, watch out for your providers for NonExistentClass errors.

I had the same issue recently. As I sometimes commit through the Android Studio (3.4.c6) I use the «Optimize imports» option to remove unused imports. For some reason, it removed the import for the Parcelize annotation.

It appeared the errors after I upgraded the .gradle version.

Upgraded the version for mockito from 2.7.21 to 2.+ fixed the issue for me.

If you come across this problem after Android X migration and start loosing your mind here is one thing you can try.

My Case:

Our project had few modules in it, lets call one of them myModuleProject . After migration to Android X it was compiling and running fine if I run it from android studio, but when code moved to cloud and CI starts build, it was failing with ‘:myModuleProject:kaptDebugKotlin’ and with long list of errors such as

After two days of nightmare I found that not only root project gradle.properties but also module projects should include following!

It seems kapt cannot find the class, or cannot determine which class to use. e.g.

I had a project with Dagger injecting something into Presenters At one moment I got a persistent «NonExistentClass.java:3: error: error.NonExistentClass must be INTERFACE» error

The root cause was trivial: a rogue copy of the valid @Inject annotated file with unsatisfied dependencies somehow slipped into the project. How can we find it? The project in Android Studio looks OK.

Look at the error message, it looks like:

/home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug/error/NonExistentClass.java:3: error: error.NonExistentClass must be INTERFACE public final class NonExistentClass <

Search at the compiled by kapt build files in /home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug /app for «NonExistentClass» string

You will find the exact file with the exact unsatisfied Dagger dependency (in my case it was a rogue orphan file in the place where it shouldn’t exist)

Источник

NonExistentClass не может быть преобразован в аннотацию

Я добавил новый интерфейс Retrofit в свой проект, содержащий пару конечных точек, аннотированных аннотациями @GET и @HEADERS , после внедрения указанного интерфейса в класс репозитория с использованием аннотации @Inject в конструкторе указанного класса, Android Studio выдает эту ошибку:

Взглянув на сгенерированный код Java, он заменяет аннотации @GET и @HEADERS следующим:

Я уже пробовал следующее:

Использование annotatioProcessor вместо kapt

Настройка jetifier.enabled на false в gradle.properties

Настройка generateStubs на true в моем файле build.gradle

Настройка correctErrorTypes на true в моем файле build.gradle

может быть дело в прицеле кинжала? или Retrofit/dagger не полностью совместим с новыми версиями плагина Kapt?

Можете ли вы показать код?

Я нашел решение, мой проект многомодульный, а модуль remote содержал зависимость retrofit , по какой-то причине IDE позволяет получить доступ к зависимостям модуля remote от модуля app , добавление зависимостей retrofit к модулю решило проблему.

Спасибо @AlfredoBejarano. Я разобрался со своей проблемой, это заняло у меня больше времени, чем я думал, но ошибка для меня была на самом деле очень явной. Я добавлю ответ, который может помочь другим.

К счастью, этот вопрос помог мне разобраться в моей проблеме. Перемещая классы из модуля приложения в библиотеку, я ссылался на класс аннотаций, который существовал только в папке отладки. Таким образом, отладочные сборки были в порядке, но вызовы gradlew install не удались при создании файлов выпуска.

Ошибка для меня была очень явной, хотя мне потребовалось много времени, чтобы понять — сгенерированный файл буквально заменил отсутствующую аннотацию на @error.NonExistentClass() .

Перемещение файла в основной набор src означало, что и отладочная, и выпускная сборки могли видеть класс. Мне потребовалось некоторое время, чтобы понять, что я предположил, что это была проблема с Dagger, замаскированная kapt, но на самом деле это была обычная старая проблема с Dagger. Мой совет: внимательно посмотрите на настройки Dagger.

Я думаю, хитрость здесь в том, что если бы вы зависели от модуля, который зависел от другого модуля/библиотеки (например, Retrofit), но вы установили Retrofit как зависимость implementation вместо зависимости api , то ваш модуль не увидел бы его транзитивно, и kapt потерпит неудачу.

Источник

ОШИБКА: error.NonExistentClass Kotlin В многомодульном проекте Dagger

Я использую Dagger 2 и Kotlin для разработки под Android. Мой проект также является многомодульным проектом. Мой файл settings.gradle выглядит так:

Я также поддерживаю модуль lib.

В Dagger Files (например, в компоненте) я пытаюсь получить предмет из другого модуля. Например:

Объект Presenter определен в модуле lib. Я работал в среде Linux, и я использую Android Studio 3 Preview Canary 5. Код работает хорошо, и я могу генерировать APK.

Но моя компания хотела создать APK, используя стабильную версию Android Studio. Я использую Android Studio 2.3.3.

При компиляции Android Project я столкнулся с этой ошибкой:

Ошибка появляется, когда

Выполняется и вызван тем, что класс кинжала не найден, класс определен в другом проекте. Какой может быть возможный обходной путь для этого? Извините за мой плохой английский.

14 ответов

Коренная причина

По сути, мало что можно сделать, чтобы исправить это при использовании kapt . Цитировать эту ссылку, которая решает ту же проблему в другой библиотеке, которая использует предварительно -процессоры (OrmaDatabase):

Поскольку Kotlin делает свои заглушки до запуска Java Annotation Processing, Kotlin просто ничего не знает об OrmaDatabase, и имя объявления в заглушках будет error.NonExistentClass. Это нарушает инструмент обработки аннотаций. Это своего рода ограничение капт

Как это исправить (обходной путь)

Просто используйте обычный apt или annotationProcessor для запуска компилятора Dagger. Как только я изменился:

В моем файле уровня модуля build.gradle я смог получить ошибки. После того, как вы исправили ошибки, вы должны вернуть строку обратно к kapt , потому что иначе классы кинжалов не были бы сгенерированы, так как они определены в Kotlin.

У меня была очень похожая ситуация с ошибкой NonExistentClass в многомодульном проекте с использованием Dagger, и оказалось, что я забыл добавить зависимость от библиотеки kotlin. Итак, просто добавив его в подмодуль, я решил мою проблему:

В моем случае у меня была @Nullable аннотация из support-annotations , а я ее удалил, чтобы перейти на AndroidX .
При создании, поскольку аннотация была импортирована неправильно, она была обнаружена как недействительная.

Я проверил код и исправил весь импорт.

Я нашел, если вы используете

Изменение на false будет представлять фактическую ошибку, вероятно, у вас будут проблемы со сборкой Dagger Graph после исправления проблем с компиляцией, но просто вернитесь к true, и вы должны быть хорошими

Я получил эту ошибку, когда в моем классе Injected произошла ошибка компиляции. Пожалуйста, убедитесь, что нет ошибок компиляции.

Кажется, есть ошибка с каптом, очистка проекта должна помочь.

Кажется, Капт не может найти класс или не может определить, какой класс использовать. например

У меня был проект с Dagger, который что-то вводил в Presenters В какой-то момент у меня возникла стойкая «NonExistentClass.java:3: error: error.NonExistentClass must be INTERFACE» ошибка

Основная причина была тривиальной: в проект каким-то образом проскользнула ложная копия действительного аннотированного файла @Inject с неудовлетворенными зависимостями. Как его найти? Проект в Android Studio выглядит нормально.

Посмотрите на сообщение об ошибке, оно выглядит так:

/home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug/error/NonExistentClass.java:3: error: error.NonExistentClass должен быть ИНТЕРФЕЙСОМ public final class NonExistentClass <

Искать в скомпилированных файлах сборки kapt в /home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug / app для строки «NonExistentClass»

Вы найдете точный файл с точной неудовлетворенной зависимостью Dagger (в моем случае это был мошеннический файл-сирота в том месте, где он не должен существовать)

Tldr: измените kapt на annotationProcessor в build.gradle, и вы увидите реальную проблему.

Я получил ту же ошибку, и оказалось, что я только что закомментировал класс, который я использовал в своем AppComponent. К сожалению, инструмент kapt не дал мне правильное сообщение об ошибке. Если вы измените kapt на annotationProcessor в компиляторе вашей библиотеки и попытаетесь собрать его, это тоже не удастся, но вы получите более подробное сообщение об ошибке.

Просто добавьте это для создания файла gradle, чтобы избежать проблем, связанных с NonExistentClass

У меня недавно была такая же проблема. Поскольку я иногда выполняю фиксацию через Android Studio (3.4.c6), я использую опцию «Оптимизировать импорт», чтобы удалить неиспользуемый импорт. По некоторым причинам он удалил импорт для аннотации Parcelize.

Если вы столкнетесь с этой проблемой после миграции Android X и начнете сходить с ума, вот одна из вещей, которую вы можете попробовать.

Мое дело:

В нашем проекте было мало модулей, давайте назовем один из них myModuleProject . После перехода на Android X он компилировался и работал нормально, если я запускаю его из android studio, но когда код перемещается в облако и CI начинает сборку, происходит сбой с ‘:myModuleProject:kaptDebugKotlin’ и длинным списком ошибок, таких как

После двух дней кошмара я обнаружил, что не только корневой проект gradle.properties , но и проекты модулей должны включать следующее!

После обновления версии .gradle появились ошибки.

Обновил версию для mockito с 2.7.21 до 2. + исправил проблему для меня.

Я получил эту ошибку, когда по ошибке переместил тестовый класс в свой основной источник. Перемещение его обратно на тестовый источник избавило от ошибки.

Источник

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
June 11, 2021

Popularity
7/10

Helpfulness
1/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • error: incompatible types: NonExistentClass cannot be converted to Annotation
  • Related Problems

  • error: incompatible types: nonexistentclass cannot be converted to annotation
  • object of class stdclass could not be converted to int in jwt.php
  • TPC Matrix View Full Screen

    error: incompatible types: NonExistentClass cannot be converted to Annotation

    Comment

    -1


    Popularity

    7/10 Helpfulness
    1/10
    Language
    java

    Source: stackoverflow.com

    Tags: java

    Contributed on Jun 11 2021

    25 Answers  Avg Quality 4/10


    Я использую Dagger 2 и Kotlin для разработки под Android. Мой проект также является многомодульным проектом. Мой файл settings.gradle выглядит так:

    include :app
    include :lib
    

    Я также поддерживаю модуль lib.

    В Dagger Files (например, в компоненте) я пытаюсь получить предмет из другого модуля. Например:

    @Component
    interface AppComponent{
        fun getPresenter() : Presenter
    }
    

    Объект Presenter определен в модуле lib. Я работал в среде Linux, и я использую Android Studio 3 Preview Canary 5. Код работает хорошо, и я могу генерировать APK.

    Но моя компания хотела создать APK, используя стабильную версию Android Studio. Я использую Android Studio 2.3.3.

    При компиляции Android Project я столкнулся с этой ошибкой:

    error: error.NonExistentClass
    

    Ошибка появляется, когда

    :app:kaptDebugKotlin 
    

    Выполняется и вызван тем, что класс кинжала не найден, класс определен в другом проекте. Какой может быть возможный обходной путь для этого? Извините за мой плохой английский.

    14 ответов

    Лучший ответ

    Коренная причина

    По сути, мало что можно сделать, чтобы исправить это при использовании kapt . Цитировать эту ссылку, которая решает ту же проблему в другой библиотеке, которая использует предварительно -процессоры (OrmaDatabase):

    Поскольку Kotlin делает свои заглушки до запуска Java Annotation Processing, Kotlin просто ничего не знает об OrmaDatabase, и имя объявления в заглушках будет error.NonExistentClass. Это нарушает инструмент обработки аннотаций. Это своего рода ограничение капт

    Как это исправить (обходной путь)

    Просто используйте обычный apt или annotationProcessor для запуска компилятора Dagger. Как только я изменился:

    kapt libs.daggerCompiler
    

    Кому

    annotationProcessor libs.daggerCompiler
    

    В моем файле уровня модуля build.gradle я смог получить ошибки. После того, как вы исправили ошибки, вы должны вернуть строку обратно к kapt, потому что иначе классы кинжалов не были бы сгенерированы, так как они определены в Kotlin.


    29

    Iman Akbari
    29 Июл 2017 в 10:05

    У меня была очень похожая ситуация с ошибкой NonExistentClass в многомодульном проекте с использованием Dagger, и оказалось, что я забыл добавить зависимость от библиотеки kotlin. Итак, просто добавив его в подмодуль, я решил мою проблему:

    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$rootProject.kotlinVersion"
    


    5

    GoRoS
    27 Авг 2018 в 11:18

    В моем случае у меня была @Nullable аннотация из support-annotations , а я ее удалил, чтобы перейти на AndroidX.
    При создании, поскольку аннотация была импортирована неправильно, она была обнаружена как недействительная.

    Я проверил код и исправил весь импорт.


    3

    Mahdi-Malv
    25 Май 2019 в 10:53

    Я нашел, если вы используете

        kapt {
        generateStubs = true
    }
    

    Изменение на false будет представлять фактическую ошибку, вероятно, у вас будут проблемы со сборкой Dagger Graph после исправления проблем с компиляцией, но просто вернитесь к true, и вы должны быть хорошими


    1

    ngatirauks
    7 Окт 2017 в 09:17

    Я получил эту ошибку, когда в моем классе Injected произошла ошибка компиляции. Пожалуйста, убедитесь, что нет ошибок компиляции.


    1

    Anuj Garg
    20 Авг 2019 в 09:50

    Кажется, есть ошибка с каптом, очистка проекта должна помочь.

    ./gradlew clean
    


    0

    ArtKorchagin
    14 Июл 2017 в 12:51

    Кажется, Капт не может найти класс или не может определить, какой класс использовать. например

    import foo.*  // class foo.Abc
    import bar.*  // annotation bar.Abc
    
    @Abc
    class Xyz { ... }
    


    0

    Wang Qian
    14 Июн 2019 в 08:50

    У меня был проект с Dagger, который что-то вводил в Presenters В какой-то момент у меня возникла стойкая "NonExistentClass.java:3: error: error.NonExistentClass must be INTERFACE" ошибка

    Основная причина была тривиальной: в проект каким-то образом проскользнула ложная копия действительного аннотированного файла @Inject с неудовлетворенными зависимостями. Как его найти? Проект в Android Studio выглядит нормально.

    1. Посмотрите на сообщение об ошибке, оно выглядит так:

      /home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug/error/NonExistentClass.java:3: error: error.NonExistentClass должен быть ИНТЕРФЕЙСОМ public final class NonExistentClass {

    2. Искать в скомпилированных файлах сборки kapt в /home/alex/AndroidProvects/TopProject/app/build/tmp/kapt3/stubs/onlineDebug / app для строки «NonExistentClass»

    3. Вы найдете точный файл с точной неудовлетворенной зависимостью Dagger (в моем случае это был мошеннический файл-сирота в том месте, где он не должен существовать)


    0

    Alex Burov
    26 Июл 2020 в 15:56

    Tldr: измените kapt на annotationProcessor в build.gradle, и вы увидите реальную проблему.

    Я получил ту же ошибку, и оказалось, что я только что закомментировал класс, который я использовал в своем AppComponent. К сожалению, инструмент kapt не дал мне правильное сообщение об ошибке. Если вы измените kapt на annotationProcessor в компиляторе вашей библиотеки и попытаетесь собрать его, это тоже не удастся, но вы получите более подробное сообщение об ошибке.


    4

    Andras Kloczl
    11 Дек 2017 в 00:50

    У меня недавно была такая же проблема. Поскольку я иногда выполняю фиксацию через Android Studio (3.4.c6), я использую опцию «Оптимизировать импорт», чтобы удалить неиспользуемый импорт. По некоторым причинам он удалил импорт для аннотации Parcelize.


    0

    mjurekov
    20 Дек 2018 в 09:20

    Если вы столкнетесь с этой проблемой после миграции Android X и начнете сходить с ума, вот одна из вещей, которую вы можете попробовать.

    Мое дело:

    В нашем проекте было мало модулей, давайте назовем один из них myModuleProject. После перехода на Android X он компилировался и работал нормально, если я запускаю его из android studio, но когда код перемещается в облако и CI начинает сборку, происходит сбой с ':myModuleProject:kaptDebugKotlin' и длинным списком ошибок, таких как

    e: /home/circleci/code/myModuleProject/build/tmp/kapt3/stubs/debug/package_name_here/reporter/bindingadapter/SomeBindingAdapterKt.java:14: error: incompatible types: NonExistentClass cannot be converted to Annotation
    @error.NonExistentClass()
    

    После двух дней кошмара я обнаружил, что не только корневой проект gradle.properties, но и проекты модулей должны включать следующее!

    android.databinding.enableV2=true
    android.useAndroidX=true
    android.enableJetifier=true
    


    -1

    Vilen
    4 Май 2019 в 10:38

    После обновления версии .gradle появились ошибки.

    Обновил версию для mockito с 2.7.21 до 2. + исправил проблему для меня.

    -    androidTestCompile "org.mockito:mockito-android:2.7.21" // remove this
    +    androidTestCompile "org.mockito:mockito-android:2.+"    // add this
    


    0

    Allen
    3 Май 2019 в 16:47

    Я получил эту ошибку, когда по ошибке переместил тестовый класс в свой основной источник. Перемещение его обратно на тестовый источник избавило от ошибки.


    1

    alexy
    12 Июл 2019 в 10:11

    Questions : NonExistentClass cannot be converted to Annotation

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00

    754

    I added a new Retrofit interface to my post uvdos retrofit2 project containing a couple of Endpoints post uvdos retrofit2 annotated with the @GET and @HEADERS post uvdos retrofit2 annotations, after Injecting said interface post uvdos retrofit2 to a repository class using the @Inject post uvdos retrofit2 annotation in the constructor of said class, post uvdos retrofit2 Android Studio throws this error:

    NonExistentClass cannot be converted to Annotation
    

    After taking a look at the generated Java post uvdos retrofit2 code, it replaces the @GET and @HEADERS post uvdos retrofit2 annotations with this:

    @error.NonExistentClass()
    

    I’ve already tried the following:

    • Using annotatioProcessor instead of kapt

    • Setting jetifier.enabled to false in post uvdos retrofit2 gradle.properties

    • Setting generateStubs to true in my post uvdos retrofit2 build.gradle file

    • Setting correctErrorTypes to true in my post uvdos retrofit2 build.gradle file

    Im using:

    • Android Studio 3.3

    • Kotlin 1.3.11

    • Dagger 2.21

    • Retrofit 2.3.0

    • Kotlin

    • Kapt

    could it be some dagger scope issue? or post uvdos retrofit2 Retrofit / dagger not fully compatible with post uvdos retrofit2 the new versions of the Kapt plugin?

    Total Answers 5

    32

    Answers 1 : of NonExistentClass cannot be converted to Annotation

    Luckily this question led me to figure help uvdos android out my issue. While moving around help uvdos android classes from an app module into a help uvdos android library, I was referencing an annotation help uvdos android class which only existed in a debug help uvdos android folder. So debug builds were fine, but help uvdos android calls to gradlew install failed when help uvdos android generating release files.

    The error for me was very explicit help uvdos android although it took me a long time to help uvdos android realize — the generated file had help uvdos android literally replaced the missing help uvdos android annotation with help uvdos android @error.NonExistentClass()

    Moving the file into the main src set help uvdos android meant both debug and release builds help uvdos android could see the class. What took me a help uvdos android while to figure out was that I assumed help uvdos android this was a Dagger issue being masked by help uvdos android kapt, but really it was just a regular help uvdos android old Dagger issue. My advice is to look help uvdos android at your Dagger setup carefully.

    0

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00Answer Link

    mRahman

    5

    Answers 2 : of NonExistentClass cannot be converted to Annotation

    For me, I had recently removed dagger help uvdos android from a project and forgot to remove the help uvdos android @Singleton and @Inject annotations from help uvdos android relevant classes.

    0

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00Answer Link

    yousuf

    3

    Answers 3 : of NonExistentClass cannot be converted to Annotation

    For me, its painfully removing all the help uvdos android @Singleton and @OpenForTesting on my help uvdos android Module classes. And removing two DAO help uvdos android classes and Repository whose backing help uvdos android model classes is no longer annotated help uvdos android with @Entity.

    0

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00Answer Link

    yousuf

    6

    Answers 4 : of NonExistentClass cannot be converted to Annotation

    For me was in here:

    apply plugin: help uvdos android ‘kotlin-android-extensions’

    0

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00Answer Link

    rohim

    1

    Answers 5 : of NonExistentClass cannot be converted to Annotation

    In my case I was using this help uvdos android «»com.fasterxml.jackson.core:jackson-databind:2.7.3» help uvdos android library, but later I removed this help uvdos android dependency from gradle, but didn’t help uvdos android remove the code that I was using of this help uvdos android library, so removed code and annotations help uvdos android related to this library solved my help uvdos android problem.

    0

    2023-02-06T14:03:40+00:00 2023-02-06T14:03:40+00:00Answer Link

    joya

    Понравилась статья? Поделить с друзьями:
  • Error incompatible types in assignment
  • Error incompatible types got single expected smallint
  • Error incompatible types got real expected smallint
  • Error incompatible types got extended expected smallint
  • Error incompatible types got extended expected longint