Error cannot find symbol lombok gradle

I have a JHipster project in which I have added dependency for Lombok in build.gradle: compile group: 'org.projectlombok', name: 'lombok', version: lombok_version And I have the Lombok plugin sta...

I have a JHipster project in which I have added dependency for Lombok in build.gradle:

compile group: 'org.projectlombok', name: 'lombok', version: lombok_version

And I have the Lombok plugin stalled for IntelliJ. I’ve turned on annotation processing in IntelliJ, I can build without errors from the IntelliJ IDE, but when I try to build from the command line I get build errors. It seems like Gradle is not processing the annotations and can’t find the getter/setter and log declarations. The project also runs without any kind of errors.

Command Line:

./gradlew build

Errors :

/Users/.../source/v4.0/src/main/java/com/.../service/MyService.java:145: error: cannot find symbol
        log.info("Security Context: " + SecurityUtils.getCurrentUserLogin());
        ^
  symbol:   variable log
  location: class MyService

Error:

/Users/.../source/v4.0/src/main/java/com/.../service/MyService.java:105: error: cannot find symbol
        myClass.setDescription(description);
                        ^
  symbol:   method setDescription(String)
  location: variable myClass of type MyClass

Service Class:

import lombok.extern.slf4j.Slf4j; 
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MyService {      
    public void someMethod(){
        log.debug("Security Context: " + SecurityUtils.getCurrentUserLogin());
        MyClass myCLass = new MyClass();
        myClass.setDescription(description);
    }
}

Entity Class:

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.Table;

@Entity
@Table(name="t_juror_file_update")
@Getter
@Setter
@NoArgsConstructor
public class MyClass {

    private String description;

}

I’ve been trying to figure this out for hours, but totally stuck. Any help would be appreciated.

Содержание

  1. Doesn’t compile with Gradle 5 RC #1945
  2. Comments
  3. Short description
  4. Expected behavior
  5. Version information
  6. Steps to reproduce
  7. Cannot find Symbol error while using Lombok Annotations. #1449
  8. Comments
  9. Lombok/Mapstruct problem: Cannot find symbol #1270
  10. Comments
  11. How to Resolve The Cannot Find Symbol Error in Java
  12. Introduction to Symbol Tables
  13. Cannot Find Symbol Error
  14. What Causes the Cannot Find Symbol Error
  15. Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol
  16. Cannot Find Symbol Error Examples
  17. Undeclared variable

Doesn’t compile with Gradle 5 RC #1945

Short description

Doesn’t compile with Gradle 5 RC

Expected behavior

Version information

  • IDEA Version:
    IntelliJ IDEA 2018.3 EAP (Community Edition)
    Build #IC-183.4284.36, built on November 7, 2018
  • JDK Version: 11.0.1
  • OS Type & Version: macOS 10.14.1
  • Lombok Plugin Version: v0.22.IDEA-EAP
  • Lombok Dependency Version: 1.18.4
  • Gradle Wrapper Version: gradle-5.0-20181112000030+0000

Steps to reproduce

None of the Lombok annotations work. All of the following are red.

The text was updated successfully, but these errors were encountered:

this work for me with gradle 5.0 release

@z0mb1ek What works — command line build works? Does IntelliJ work? Do you’ve a sample project that you can share?

Same problem for me with gradle 5.0 RELEASE.

Command line works, but intellij not.

I can fix it be changing the dependency to compile instead of compileOnly

Disclaimer: I’m not a project member and I’m not gonna fix it; I just hope that answering my questions could help those who will.

@mmoayyed No idea, but isn’t it a problem of the plugin? If so, then please use the proper issue tracker as it’s a separate project.

Update: @asarkar Apologies, I totally missed the link.

Otherwise, some information is needed about where it broken. Was it gradle 5.0 or was it Lombok 1.18.4? IOW what related versions do work?

@Maaartinus, did you see that in the original problem description, I’ve put a link to the IntelliJ plugin issue tracker, who claimed that the problem isn’t on their end? This sort of finger pointing isn’t representative of adult coders; someone needs to own the problem, and stop the buck from passing around. That doesn’t mean they must fix it immediately, but at least take responsibility.

@randakar I didn’t say @Maaartinus should pick up this ticket; I’m sure he can speak for himself, so I’ll instead focus on what you called out.
Lombok docs that you referred to seem to be outdated, which is somewhat clear from the heading «Gradle v2.12 and up».
See this discussion in Gradle forum. Gradle 5 onwards, Lombok needs to be registered as an annotation processor.

@asarkar have you retried since the first release of Gradle 5 ? Personally my project compiles correctly but my IDE (intellij) cannot resolve lombok’s annotation anymore. So I think there might be a problem with the plugin as you stated in your first issue.

by the way it builds correctly by using

but there are no reasons why it would not work with compileOnly , which worked correctly in Gradle 4.7+.

by the way it builds correctly by using

but there are no reasons why it would not work with compileOnly , which worked correctly in Gradle 4.7+.

Please check your final artifact. I use Lombok in a Spring Boot project and if I change from «compileOnly» to «Implementation» Gradle 5 includes Lombok JAR in /BOOT-INF/lib as runtime dependency.

probably related and caused by this one https://youtrack.jetbrains.com/issue/IDEA-201974, latest RC — works for me. (mind the caches)

@risbarov indeed, implementation is not a viable solution

IntelliJ IDEA 2018.3 EAP is working for me as well.

So this issue here is not related to Lombok and could be closed, right?

I think this is still a problem.
Using gradle 5.0 (release) together with lombok 1.18.4 does not compile.

Task :compileJava FAILED
/home/travis/build/LarsEckart/gradle5lombok/src/main/java/gradle5lombok/App.java:16: error: cannot find symbol
log.info(«logging Hello World»);
^
symbol: variable log
location: class App
1 error
FAILURE: Build failed with an exception.

When i downgrade to gradle wrapper 4.10.2, it compiles.

hm, ok, I had a close look at your project and one difference I spotted was that you not only declare lombok dependency as compileOnly, but also additionally as annotationProcessor dependency. When adding that line to my project, it indeed works. Will have to have a closer look at gradle documentation about annotation processors.
Thanks a lot for getting back to me and resolving this issue. Can also update my colleagues then who came to me today with the same problem 😉

I think this is still a problem.
Using gradle 5.0 (release) together with lombok 1.18.4 does not compile.

Task :compileJava FAILED
/home/travis/build/LarsEckart/gradle5lombok/src/main/java/gradle5lombok/App.java:16: error: cannot find symbol
log.info(«logging Hello World»);
^
symbol: variable log
location: class App
1 error
FAILURE: Build failed with an exception.

When i downgrade to gradle wrapper 4.10.2, it compiles.

Same as here. Did anyone discover why it does not compile in Gradle 5?

I think this is still a problem.
Using gradle 5.0 (release) together with lombok 1.18.4 does not compile.
https://github.com/LarsEckart/gradle5lombok
both on my laptop and travis-ci I get:

Task :compileJava FAILED
/home/travis/build/LarsEckart/gradle5lombok/src/main/java/gradle5lombok/App.java:16: error: cannot find symbol
log.info(«logging Hello World»);
^
symbol: variable log
location: class App
1 error
FAILURE: Build failed with an exception.

When i downgrade to gradle wrapper 4.10.2, it compiles.

Same as here. Did anyone discover why it does not compile in Gradle 5?

also have the problem, lombok 1.18.6 does not work on the console with Gradle 5.x.
I am also interested in the solution, for me

does not work in the console
. error: cannot find symbol

I am facing the same issue JDK 11, Gradle 5+ and lombok 1.18.6 with Eclipse.
Eclips plugin seems fine but command line is broken.
I have exact same problem as @ingoschaal

@ingoschaal and @hiteshbargujar, are you using the literal string $lombokVersion in your build.gradle file or did you replace it with your actual Lombok version? (Maybe you have solved this already.)

I initially had compilation issues on the command line, using the gradle wrapper (gradlew), after simultaneously upgrading from Gradle 4.10.* to 5.4.1 and from Lombok 1.18.4 to 1.18.6. When I added annotationProcessor ‘org.projectlombok:lombok:1.18.6’ in the dependencies section, this solved my compilation issues. (Looking at the changelog for Lombok and also at previous comments here (and at the title of this issue), my compilation issues appear to have been more to do with configuring Gradle correctly than with changing the Lombok version.)

@asarkar suggesting that the maintainers of an open source project are not ‘adult coders’ or are ‘passing the buck around’ is not acceptable. I understand that you may feel frustrated that stuff breaks and you now need to do extra work, whilst all you were doing was upgrading a few tools and libraries to newer versions. That doesn’t give you the excuse to make demands.

@ingoschaal @hiteshbargujar please note @RohanTalip ‘s comment; the gradle docs don’t reference 2.12 anymore, we fixed a bunch of gradle things, I read multiple reports that all is well, so I’m closing this. If you still have issues, open a new bug report and give us A LOT more information and something to allow us to reproduce the issue.

@rzwitserloot whatever is said is backed by evidence, so it’s true. Also, the same comment that you referred to also says “that doesn’t mean they should fix it immediately”, so no demand was made. What is not acceptable is you calling people out wrongly.

I understand that it must feel good to exercise you commit privilege and close the ticket, but you haven’t provided any solutions. You simply asked the reporters of this problem to open another ticket for the same issue if it persists.

we solved it the easy way, we are deprecating the use of Lombok dependencies in our code. We are almost complete refactoring.

@ingoschaal and @hiteshbargujar, are you using the literal string $lombokVersion in your build.gradle file or did you replace it with your actual Lombok version? (Maybe you have solved this already.)

I initially had compilation issues on the command line, using the gradle wrapper (gradlew), after simultaneously upgrading from Gradle 4.10.* to 5.4.1 and from Lombok 1.18.4 to 1.18.6. When I added annotationProcessor ‘org.projectlombok:lombok:1.18.6’ in the dependencies section, this solved my compilation issues. (Looking at the changelog for Lombok and also at previous comments here (and at the title of this issue), my compilation issues appear to have been more to do with configuring Gradle correctly than with changing the Lombok version.)

annotationProcessor ‘org.projectlombok:lombok:1.18.6’ in the dependencies section,
thanks thats works

I had the same issues with Gradle 5.4.1 and lombok 1.18.1 (while everything worked fine under Gradle 4.10.2), and eventually found this, which solved the issues:

Источник

Cannot find Symbol error while using Lombok Annotations. #1449

I am getting below error while using the lombok.

cannot find symbol
[ERROR] symbol: method builder()
[ERROR] symbol: getXXXXXX()

below are the annotation, I am using.

Maven version is 3.5.0
Below is the pom.xml entries.

Please advise what is this issue?

The text was updated successfully, but these errors were encountered:

Was able to resolve my issue. Did not realize that variables declared final had no setter.

I got the solution of this problem. I had to remove -proc:none that was preventing the lombok annotation to be processed.

I got the solution of this problem. I had to remove -proc:none that was preventing the lombok annotation to be processed.
@mukeshkamboj Thanks Mukesh! I just tried every damn thing with my intellij. Your comment helped me to get rid of the issue.

Regards,
Bhargav
Love all, Serve all !

hi, where is the -proc:none located?

I got the solution of this problem. I had to remove -proc:none that was preventing the lombok annotation to be processed.

i don’t know but it solve my problem.

i have two classes use @builder to generate build method. but one is normal, another is abnormal,everything check is ok. but when i run mvn to compile my project, the error as fellow:

can’t not find the symbol method builder()

i try to replace the version of the lombok jar, but even through i make the version is latest, it’s not ok.

so, i try to import lombok per class that i reference.

Источник

Lombok/Mapstruct problem: Cannot find symbol #1270

Hi, I love MapStruct and Lombok, but I get a «cannot find symbol» error when compiling with Maven from command-line using Javac.

In some setups, it is the @Mapper annotation that cannot be found, in other setups it is the calls to the Lombok-generated getters/setters etc.

I have created a minimal test-project that demonstrates the error. Code, pom file, stacktrace, Java-version, Maven-version, dependencies etc are all described in the zip-folder files.

I am using maven-compiler-plugin version 3.6.1, mapstruct-jdk8 version 1.2.0.CR1 and lombok version 1.16.16. And the project is a spring-boot application.

Note that this issue resembles #841, which recommends to exlude the transitive mapstruct dependency pulled in from the dependency to springfox-swagger2. This, however, did not solve the problem.

This is the output from mvn clean verify :

The text was updated successfully, but these errors were encountered:

By downgrading the maven-compiler-plugin from 3.6.1 to 3.1 I got it to work.
I trimmed the attached pom further to pindown the problem, and this is the new pom (with the downgraded plugin version that makes it compile):

I will leave the issue open in case this is a bug — it is possible that I have missed this requirement in some documentation.

Thanks for the nice words. We are glad that you like MapStruct 😄 .

The problem is that you have only mapstruct-processor in the annotationProcessorPaths and only that dependency is passed to the javac compiler.

The annotationProcessorPaths is there only since 3.5 so it is really strange how the mapstruct processor is invoked. In any case in order to make it work correctly you have 2 options:

Add the lombok dependency to the annotationProcessorPaths as well. Then it will be picked up by the compiler and it should work.

Ad the mapstruct-processor jar to your pom as a provided dependency. You will have to remove the annotationProcessorPaths in that case and the compiler will pick up the processors from your dependency. The reason why we are suggesting to use the annotationProcessorPaths is because by doing that you won’t be able to use something from the mapstruct-processor module by accident. An additional reason to put it in the pom dependencies is this issue from IntelliJ (in case you are using InteliiJ 😄

You can also have a look at the mapstruct-lombok example from our repository.

I am going to close this issue as it is a problem in the configuration 😄

Источник

How to Resolve The Cannot Find Symbol Error in Java

Table of Contents

Introduction to Symbol Tables

Symbol tables are an important data structure created and maintained by compilers to store information associated with identifiers [1] in a given source code. This information is entered into the symbol tables during lexical and syntax analysis and is used in the later phases of compilation. As the declarations of classes, interfaces, variables, and methods are processed, their identifiers are bound to corresponding entries in the symbol tables. When uses of these identifiers are encountered in the source code, the compiler looks them up in the symbol tables and relies on this information for things such as verifying that a variable has been declared, determining the scope of a variable, and verifying that an expression is semantically correct with type checking. Symbol tables are also used for code generation and optimization [2].

A simplified representation of a symbol table entry (or simply, a symbol) in Java has the following format: . Given a global variable declaration like final double ratio; the corresponding symbol would then be .

Cannot Find Symbol Error

As its name implies, the cannot find symbol error refers to a symbol which cannot be found. While there are multiple ways and reasons this can occur, they all boil down to the fact that the Java compiler is unable to find the symbol associated with a given identifier.

The message produced by the compiler for the cannot find symbol error includes two additional fields:

  • “symbol”—the name and type of the referenced identifier; and
  • “location”—the specific class in which the identifier has been referenced.

What Causes the Cannot Find Symbol Error

The most common triggers for the cannot find symbol compile-time error include:

  • missing variable and method declarations;
  • out-of-scope references to variables and methods;
  • misspelled identifiers; and
  • omitted import statements.

Cannot Find Symbol vs Symbol Not Found vs Cannot Resolve Symbol

As different Java compilers use slightly different terminology, the cannot find symbol error can also be found under the terms symbol not found and cannot resolve symbol . Besides the naming, there is no difference between what these terms stand for.

Cannot Find Symbol Error Examples

Undeclared variable

When the Java compiler encounters a use of an identifier which it cannot find in the symbol table, it raises the cannot find symbol error. Consequently, the most common occurrence of this error is when there is a reference to an undeclared variable. Unlike some other languages that don’t require explicit declaration of variables [3], or may allow declaring a variable after it has been referenced (via hoisting [4]), Java requires declaring a variable before it can be used or referenced in any way.

Fig. 1(a) shows how an undeclared variable, in this case the identifier average on line 9, results in two instances of the cannot find symbol error, at the positions where they appear in the code. Declaring this variable by specifying its data type (or, alternatively, inferring its type with the var keyword in Java 10+) resolves the issue (Fig. 1(b)).

Источник

#java #gradle #lombok #intellij-lombok-plugin

Вопрос:

Я столкнулся с проблемой при создании своего проекта, в котором используется Ломбок, после перехода в другую ветвь git. Я получаю несколько исключений, как правило, из этих двух типов:

  1. для таких занятий, как
 @Setter(onMethod_ = @Autowired)
public class ClassA{

   private ClassC c;

}
 

Я получаю

 java: cannot find symbol
  symbol:   method onMethod_()
  location: @interface lombok.Setter
 
  1. для таких занятий, как
 @Builder
public class ClassB{

}
 

Я получаю

 java: cannot find symbol
  symbol:   class ClassBBuilder
  location: class com.example.application.ClassB
 

в таких методах, как

 private ClassB.ClassBBuilder getBuilder(Object input) {
    //builder init
}
 
  1. И после всего, что я получаю StackOverflowError .

Проблема устранена после запуска gradle:clean -> > gradle:build . Но появляется снова после смены ветки. Дополнительная информация: Я использую Intellij Idea 2020.3.3 Ultimate Edition , и флажок "Enable Annotation processing" установлен. Вот некоторые части моего build.gradle :

 import org.springframework.boot.gradle.plugin.SpringBootPlugin

plugins {
    id 'net.ltgt.apt' version '0.19'
    id 'net.ltgt.apt-idea' version '0.19'
    id 'org.springframework.boot' version '2.3.2.RELEASE' apply false
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'net.ltgt.apt'
apply plugin: 'net.ltgt.apt-idea'
apply plugin: 'io.spring.dependency-management'

repositories {
    maven { url = 'https://repo.maven.apache.org/maven2' }
}

dependencyManagement {
    imports {
        mavenBom SpringBootPlugin.BOM_COORDINATES
    }
}

dependencies {
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
//other dependencies
}
 

Кто-нибудь знает, что может вызвать эту проблему?

Комментарии:

1. Почему в конце есть символ подчеркивания onMethod_ ?

2. происходит ли это, когда вы пытаетесь создать свой проект в intellij? Ошибки ожидаются, если генерация кода ломбока для новых классов (из вашей новой ветви) не была запущена.

3. Я думаю, что проблема связана с вашей ide. попробуйте поменять ветку местами и обойтись gradle: build без использования intellij. Проверьте, по-прежнему ли у вас проблема.

4. @ImtiazShakilSiddique, сборка с Gradle помощью идет нормально, но когда я запускаюсь debug Intellij после этого, я все равно получаю эти ошибки.

5. Хорошо, обновление до Lombok 1.18.18 решило проблему.

Ответ №1:

Эта проблема была решена в более новой версии Lombok. Пожалуйста, обновите версию Ломбока до 1.18.18, и это исправит проблему.

Комментарии:

1. Это так глупо и неприятно. Я не могу импортировать ломбок 1.18.18 (потому что моя организация создает оболочку до того, как мы сможем использовать открытый исходный код). Я чувствую разочарование, когда решаю такие глупые проблемы с помощью фреймворка или IDE (вместо реальной работы). Я желаю, чтобы когда-нибудь этот мир стал гладким для разработчиков программного обеспечения!

Ответ №2:

Я думаю, вам нужно обновить свои зависимости от ломбока до последней версии.

Понравилась статья? Поделить с друзьями:
  • Error cannot find symbol import
  • Error cannot find symbol dagger
  • Error cannot find symbol android studio
  • Error cannot find signatures with metadata for snap
  • Error cannot find pspell