Intellij IDEA Java classes not auto compiling on save
Asked Answered
S

20

211

Yesterday I switched to IntelliJ IDEA from Eclipse.

I am using JRebel with WebSphere Server 7 as well.

Everything now seems to be working somewhat fine, except that when I modify a Java file, and hit save, IntelliJ does not re-compile the file, in order for JRebel to pick it up.

The Eclipse "Build Automatically" feature resolved this issue.

In IntelliJ IDEA, I have to hit CTRL+SHIFT+9 to re-compile the relevant class for JRebel to pick it up. If changes are done across two files, I have to do this on each and one of them and since IntelliJ uses the save all mechanism, its pretty hard to know what to recompile manually which I am not really interested in doing either.

Isn't there a way to make IntelliJ to do this on its own?

Seismology answered 5/10, 2012 at 10:27 Comment(4)
Why don't you just press Ctrl+F9? That will build the whole project and if only two files has changed then those will be rebuild.Eberta
I was afraid it would rebuild all. I believe default is clear output on rebuild ... so normally this doesnt work to good...Seismology
It does not clean before build. It's an incremental build. You have another choice to rebuild if desired.Eberta
Check this out : #19597279Bancroft
G
297

UPDATED

For IntelliJ IDEA 12+ releases we can build automatically the edited sources if we are using the external compiler option. The only thing needed is to check the option "Build project automatically", located under "Compiler" settings:

Compiler Settings

Also, if you would like to hot deploy, while the application is running or if you are using spring boot devtools you should enable the compiler.automake.allow.when.app.running from registry too. This will automatically compile your changes.

For versions greater than 2021.2, we need check 'Allow auto-make to start even id the development application is currently running' option: enter image description here

For versions older than 2021.2:

Using Ctrl+Shift+A (or +Shift+A on Mac) type Registry once the registry windows is open, locate and enable compiler.automake.allow.when.app.running, see here:

enter image description here


For versions older than 12, you can use the *EclipseMode* plugin to make IDEA automatically compile the saved files.

For more tips see the "Migrating From Eclipse to IntelliJ IDEA" guide.

Georgettegeorgi answered 5/10, 2012 at 10:35 Comment(20)
Feels annoying that I have to install a plugin for this. I already spent yesterday and today on this. I wish they could just build in an option for this, I don't think Eclipse has a patent on this feature, do they? I could also remap to CTRL + S to make as it saves automatically. I will try a couple of options. thanksSeismology
This is slow. This is too slow. There is much room for improvement! I am not what it does in the background, but it takes Intellij about 3-4 seconds to compile one small change in one single class. Even the "Compile 'StartController.java'" meaning one class only takes 3-4 seconds. Eclipse does this in less than 100 milliseconds. I will test the eclipse mode plugin again and decide what to go with..Seismology
"make project automatically" only works when not running/debuggingPronation
Not that in IntelliJ 2016.3, this option is not called Build project automatically.Titleholder
Useless for someone like me let jetty-maven-plugin running aside, I have to press CTRL+9 to manually build, any insight?Gossipmonger
Doesn't work for me with Intellij 2017.1.3 and spring boot devtools.Matelote
Don't work with IntelliJ IDEA 2017.3.3, Java 9.0.4, Spring Boot 2.0.0.RC1, Spring devtools :(Ball
@DoNhuVy have you enabled the compiler.automake.allow.when.app.running?, see my updated answer.Georgettegeorgi
I re-open for checking. I am sure 100% enable.Ball
@DoNhuVy Then you should file a bug, here: youtrack.jetbrains.comGeorgettegeorgi
still useful with IntelliJ 2018Dominiquedominium
'Clear output directory on rebuild' could be turned off to speed things up. Depends on how (well) your build-system is set up.Moguel
Worked properly after I mapped build automatically to cmd+shif+sSnips
Doesnt work 2020.4. Hey, its my question! Just discovered that. lol ... back here again I guess.Seismology
@mmm Hi, nice to "see" you again :). Are you using an EAP build, 2020.1 is the latest version right now. Maybe you are hitting a bug, have you tried with a new project and "Build project automatically" setting enabled?Georgettegeorgi
@Georgettegeorgi no, 2019.3.4.Seismology
compiler.automake.allow.wehn.app.running is awesome in that we can set once and forget. The other setting is really throwing people for a loop in that we have 10 projects and you have to go set it for ALL projects :(. is there a global setting we can tweak instead?Psychro
Not working for me. I have class A with a constant that is referenced by class B. When I make the constant in A private then IntelliJ does not tell me that I broke B with that. Even after building the project (Ctrl-F9) it does not catch up. I have to rebuild to make IntelliJ understand. Eclipse tells you right away. Anyone else having this?Frederico
@mmm here I am! 2020.3 Ultimate and same issue. Only way to make it work is to re-build the whole thigs... what a letdownBanderole
I have had this off for ages. I manually compile nowadays. Shift F8. I have no idea, but I don't think it is a good idea regardless anymore, the compiler upon errors will continue to replace code, and if you are using jrebel, things will be reloaded more often (say on every save) rather than when I am done. This makes things more fragile, as the state when changes are introduced could be in a more fragile state in between, although who knows. I don't.Seismology
P
81

Please follow both steps:

1 - Enable Automake from the compiler

  • Press: ctrl + shift + A (For Mac + shift + A)
  • Type: make project automatically
  • Hit: Enter
  • Enable Make Project automatically feature

2 - Enable Automake when the application is running

  • Press: ctrl + shift + A (For Mac + shift + A)
  • Type: Registry
  • Find the key compiler.automake.allow.when.app.running and enable it or click the checkbox next to it

Note: Restart your application now :)

Note: This should also allow live reload with spring boot devtools.

Pubis answered 24/4, 2016 at 19:1 Comment(6)
Perfect, this was just what i was looking for =)Expertise
This also worked for me with spring-boot-devtools and IntelliJ IDEA 2016.2.5Reservist
Right, so this seems to work on IntelliJ 2017.1.3, I used option 2 as this is what one needs with spring boot devtools.Matelote
Worked well but it takes 4-5 seconds to reload in JRebel. Any way around that?Wolcott
Option 2 worked for me. InteliJ 2017.3.1 Community versionUniparous
I don't think the items 1 & 2 above are "options", but are steps. You need to do both.Quinquepartite
E
68

WARNING

Eclipse Mode plug-in is obsolete and is not compatible with the recent IDEA 12+ builds. If you install it, IDE will hang on every file change and will respond extremely slow.


IntelliJ IDEA doesn't use automatic build, it detects errors on the fly, not via compiler. Similar to Eclipse mode will be available in IDEA 12:

Make project automatically

Use Build | Make, it invokes the incremental make process that will compile only changed and dependent files (it's very fast).

There is also a FAQ entry that may help.

Update on the automatic make feature: When run/debug configuration is running, Make project automatically has no effect. Classes on disk will change only on Build | Make. It's the core design decision as in our opinion class changes on disk should be always under user's control. Automatic make is not the copycat of Eclipse feature, it works differently and it's main purpose is to save time waiting for the classes to be ready when they are really needed (before running the app or tests). Automatic make doesn't replace the explicit compilation that you still need to trigger like in the case described in this question. If you are looking for different behavior, EclipseMode plug-in linked in the FAQ above would be a better choice.

Electrostriction answered 5/10, 2012 at 10:36 Comment(20)
Yeah, I had see it before, but dismissed it as being too slow, with the popup and all. Thought it was for something else. I might give a try althoguh a CTRL + 9 is annoying, but I guess I could remap to CTRL + S to make as it saves automatically.Seismology
Thanks for the update. I have installed the Eclipse Mode plugin. Don't have that dialog... Ook.. Intellij 12 ... well, good that you are improving. Is intellij 12 even out?Seismology
EAP build is linked in my answer, release will be available in December.Electrostriction
I have been trying out 12 for a couple of days. The use external build -> make automatically does not fire any action. Nothing happnes. When I use the eclipse mode plugin ( enable/disable it from settings) that works fine, but when I disable the eclipse mode plugin and enable "use external build -> auto make" nothing happens on edit and save... any idea to why?Seismology
Thanks, but I feel I just spent two weeks for nothing. CTRL + F9 is probably best option. I was afraid it would rebuild all. I believe default is clear output on rebuild, which in some cases makes Make project behave a bit unexpected..Seismology
The only problem, is that after you enable it, intellij becomes very slow (everytime I press a key it recompiles things in background).Smearcase
Does this feature update the class files when the project is on maven? Do the class files in the jar file created in the target folder get updated automatically with the changes?Clos
@Clos No, it doesn't update the jar files. You can create a new artifact for a jar and build it manually via Build | Build Artifacts or enable an option in the artifact to build it on Make.Electrostriction
@Electrostriction I just came back to this and jRebel. This is too slow. There is much room for improvement! I am not what it does in the background, but it takes Intellij about 3-4 seconds to compile one small change in one single class. Even the "Compile 'StartController.java'" meaning one class only takes 3-4 seconds. Eclipse does this in less than 100 milliseconds. I will test the plugin again and decide what to go with..Seismology
@SecretService feel free to report an issue with more details at youtrack.jetbrains.com/issues/IDEA.Electrostriction
@Electrostriction This clearly doesnt work when you are running an instance of Tomcat, so what is your suggestion around this? Install the plugin once again.. ?Seismology
Ok, had to remap the control s ... annoying and not user friendly .. everytime i go back to intellij i have to go through hell the first couple of daysSeismology
This does not work on IntelliJ Idea 13. The option says "(only works while not running / debugging)".Encratis
@Encratis it's mentioned in the answer, read below Update on the automatic make feature.Electrostriction
@Electrostriction thanks, overread that. I think IntelliJ just isn't the right tool for game development where you want to Hot Swap often :(Encratis
@lukad, Just change Ctrl+S to Build | Make as suggested below, you will get the same behavior as in Eclipse, it will save and update the changes.Electrostriction
@Electrostriction This doesn't seem to work. I just double checked that Ctrl+S is mapped to both Save All and Build | Make Project (I also tried mapping it to Build | Compile). Only Save All seems to be executed. I guess it would work If I removed the shortcut for Save All but I don't really want to do that.Encratis
@Encratis Why? Build | Make does Save All automatically.Electrostriction
@Electrostriction This is not an optimal solution and this question is obviously very popular. If the hotkey is changed, saving becomes a lag, and for us that have a habit of saving this is not a good solution. Please also allow us to pin unclosable tabs!! Please, also to preserve the tab order so that new tabs are opened to the right of all pinned tabs, or a group of pinned tabs. I am not giving up on this one!Seismology
@SecretService tab behavior suggestions are welcome at youtrack.jetbrains.com/issues/IDEA . There are already several open issues about pinned tabs and preventing them from closing.Electrostriction
C
39

You can keymap ctrl+s to save AND compile in one step. Go to the keymap settings and search for Compile.

Coplin answered 18/12, 2012 at 22:6 Comment(3)
Thanks, I like this best! The auto compile in intellij, and this one as well, but at least I see when it finishes now, is too slow.Seismology
Didn't work for me, assigning CTRL+S to compile didn't restart my server start with the debug buttonCholesterol
It works for me, Intellij 2018.2. It should search for Build ProjectKitti
G
20

There is actually no difference as both require 1 click:

  • Eclipse: manual Save, auto-compile.
  • IntelliJ: auto Save, manual compile.

Simplest solution is just to get used to it. Because when you spend most of your daytime in your IDE, then better have fast habits in one than slow habits in several of them.

Grethel answered 2/3, 2015 at 8:24 Comment(8)
There is way to improve IntelliJ experience: save and compile while you switching to browserCostumier
Eclipse has the ability to add save actions, you so can also do things like organize imports and format code on save. Doing all of these things manually adds a significant number of keystrokes and makes the process more error prone. For instance, you can never have unformatted code if you format on save in Eclipse. It's very easy to forget formatting in IntelliJ.Chaplain
@Max, IntelliJ runs those actions during commit (which to my personal taste is the best moment). In some cases it also highlights coding style problems directly in the editor (e.g. PEP8 conformance for python).Grethel
Getting used to something that one IDE does for me and another does not, making my life more difficult, is not a good selling point.Bee
@Bee improving usability very often requires dropping old, oftentimes unnecessary, habits for users.Grethel
On my MacAir I have to press fn + command + F9, this combo might become annoying, but let me give it a go ....Matelote
@NicodeWet making F1, F2 etc keys as standard function keys on Mac speeds up development quite notably.Grethel
I just used the Eclipse keymap when moving to IntelliJ anyway - so as autosave exists, instead of CNTRL + S I just use CNTRL + B for build and its instant.Cabalistic
M
17

I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s to it.

Mandal answered 23/1, 2013 at 19:15 Comment(1)
@SecretService Might not work for everyone, as the order of actions is not defined when multiple actions are mapped to the same shortcut.Geesey
S
14

I managed to solve this using macros.

I started recording a macro:

  • Click Edit - Macros - Start macro recording
  • Click File - Save All
  • Click Build - Make Project
  • Click Edit - Macros - Stop macro recording

Name it something useful like, "SaveAndMake".

Now just remove the Save all keybinding, and add the same keybinding to your macro!

So now, every time i save, it saves and makes a dirty compile, and jRebel now detects all changes correctly.

Scanties answered 27/2, 2015 at 12:18 Comment(2)
Would suggest giving the macro a different keybinding rather than replace existing save all - but that just being equally subjective.Dialyse
Thanks. Since a normal "Build" (as suggested by the other answers) is not even sufficient for me I use this solution to save + rebuild every time. Gives me back the Eclipse feeling, even if it consumes lots of resources...Frederico
L
5

Please follow these steps carefully to enable it.

1) create Spring Boot project with SB V1.3 and add "Devtools" (1*) to dependencies

2) invoke Help->Find Action... and type "Registry", in the dialog search for "automake" and enable the entry "compiler.automake.allow.when.app.running", close dialog

3) enable background compilation in Settings->Build, Execution, Deployment->Compiler "Make project automatically"

4) open Spring Boot run config, you should get warning message if everything is configured correctly

5) Run your app, change your classes on-the-fly

Please report your experiences and problems as comments to this issue.

click here for more info

Lowndes answered 2/2, 2017 at 3:42 Comment(1)
It's marked as still "In Progress", and doesn't work for me.Dime
P
3

For folks using the new Intellij version and can't find compiler.automake.allow.when.app.running

https://youtrack.jetbrains.com/issue/IDEA-274903

Basically the option has now moved to Settings -> Advanced Settings -> Compiler (Check the Allow auto-make option)

Parodist answered 9/10, 2021 at 17:45 Comment(1)
Thanks... still can't get it working though, says the live server is running but nothing happens when I change a class string.Furnace
L
3

For Intellij 2021 or later, you'll not find the registry entry

compiler.automake.allow.when.app.running

It has been moved to advanced settings as shown in the below screenshot

IntelliJ Advanced Settings Screenshot

Source: https://youtrack.jetbrains.com/issue/IDEA-274903

Litch answered 11/10, 2021 at 22:22 Comment(0)
J
2

The only thing that worked for me in my maven project that was affected by this is to add a "test-compile" goal to the run configuration of my unit tests. Incredibly clumsy solution, but it works.

enter image description here

Jamboree answered 29/4, 2017 at 11:1 Comment(1)
at least it works :D but yeah, it's better to find a source of this problemWraf
H
2

Intellij fails quietly when it encounters compile problem in other module, and then automatic build is not performed. So check your Problems window

Hussite answered 23/10, 2017 at 19:56 Comment(0)
D
2

i had same issue and also a problem file icon in intellij, so i removed the .idea folder and re import project solved my issue.

Dustup answered 4/5, 2020 at 5:29 Comment(0)
F
1

I had the same issue. I was using the "Power save mode", which prevents from compiling incrementally and showing compilation errors.

Footstone answered 26/12, 2014 at 21:12 Comment(1)
Idont know why this answer gots downvoted, its also answers the question, for me was the same - "Power save mode", although its wrote in settings, but with this enabled auto compiling doesnt work.Petuu
P
1

Use the Reformat and Compile plugin (inspired by the Save Actions plugin of Alexandre DuBreuil):

https://plugins.jetbrains.com/plugin/8231?pr=idea_ce

At the moment I am only offering a jar file, but this is the most important part of the code:

private final static Set<Document> documentsToProcess = new HashSet<Document>();
private static VirtualFile[] fileToCompile = VirtualFile.EMPTY_ARRAY;

// The plugin extends FileDocumentManagerAdapter.
// beforeDocumentSaving calls reformatAndCompile
private static void reformatAndCompile(
        @NotNull final Project project,
        @NotNull final Document document,
        @NotNull final PsiFile psiFile) {
    documentsToProcess.add(document);
    if (storage.isEnabled(Action.compileFile) && isDocumentActive(project, document)) {
        fileToCompile = isFileCompilable(project, psiFile.getVirtualFile());
    }
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            if (documentsToProcess.contains(document)) {
                documentsToProcess.remove(document);
                if (storage.isEnabled(Action.optimizeImports)
                        || storage.isEnabled(Action.reformatCode)) {
                    CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
                        @Override
                        public void run() {
                            if (storage.isEnabled(Action.optimizeImports)) {
                                new OptimizeImportsProcessor(project, psiFile)
                                    .run();
                            }
                            if (storage.isEnabled(Action.reformatCode)) {
                                new ReformatCodeProcessor(
                                        project,
                                        psiFile,
                                        null,
                                        ChangeListManager
                                            .getInstance(project)
                                            .getChange(psiFile.getVirtualFile()) != null)
                                                .run();
                            }
                            ApplicationManager.getApplication().runWriteAction(new Runnable() {
                                @Override
                                public void run() {
                                    CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(psiFile);
                                }
                            });
                        }
                    });
                }
            }

            if (fileToCompile.length > 0) {
                if (documentsToProcess.isEmpty()) {
                    compileFile(project, fileToCompile);
                    fileToCompile = VirtualFile.EMPTY_ARRAY;
                }
            } else if (storage.isEnabled(Action.makeProject)) {
                if (documentsToProcess.isEmpty()) {
                    makeProject(project);
                }
            } else {
                saveFile(project, document, psiFile.getVirtualFile());
            }
        }
    }, project.getDisposed());
}

private static void makeProject(@NotNull final Project project) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            CompilerManager.getInstance(project).make(null);
        }
    }, project.getDisposed());
}

private static void compileFile(
        @NotNull final Project project,
        @NotNull final VirtualFile[] files) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            CompilerManager.getInstance(project).compile(files, null);
        }
    }, project.getDisposed());
}

private static void saveFile(
        @NotNull final Project project,
        @NotNull final Document document,
        @NotNull final VirtualFile file) {
    ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
            final FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
            if (fileDocumentManager.isFileModified(file)) {
                fileDocumentManager.saveDocument(document);
            }
        }
    }, project.getDisposed());
}
Probative answered 1/3, 2016 at 15:43 Comment(8)
Why would anyone download some random code and run it?Confectionery
@Drew: Just uploaded it to Jetbrains for review. But if you are paranoid I suppose you could wait some days before it is available from there...Probative
sbmpost, I am merely pointing out why some would (not that I did) downvote, flag as Not An Answer, and get this deleted.Confectionery
If it is code you can post, in text, that is great. Can you? This is a code site.Confectionery
It needs source code or I would not bother. Here is a suggestion. Some site (maybe the one to which you refer) where people see the code. Like github. Then a link to that code. Then a few sentences at least to show off what it can do and some other commentary about whatever. Otherwise I would not bother. In short, without source code, this is the wrong site for this answer.Confectionery
I added the most important part of the code. I suppose I could setup a github repo, but I would first like to wait for the review.Probative
Great. Maybe walk people thru it. Very High Level. Otherwise it is a code dump. And note that you are offering up just a JAR at the moment. Thanks for sharing.Confectionery
@drew: added note about the jar and added a little more context to the code. It might seem high level, but if you extend from FileDocumentManagerAdapter and add the code, you would (almost) have a compiling ReformatAndCompile class.Probative
P
1

Edit your Run/Debug Configuration so that Build option is selected before launching

enter image description here

After Build option is selected

enter image description here

The above solution worked for me while working on my JBehave test suite

Pinchas answered 30/8, 2018 at 15:30 Comment(1)
this is nice, but the question was around auto compiling on save, without having to compile explicity again using a custom command, before doing anything like running a test, etc.,Etz
S
1

It was not working for me due to having an unnecessary module in my project structure. The tests were executed using the other module, I suppose.

I don't know how it ended up like that but removing it solved the problem.

Make sure your Run/Debug settings are using the module you are building with the autosave.

E.g. : see the module in

enter image description here

You can change the modules in Project Structure - Modules

enter image description here

Sacramentarian answered 12/3, 2019 at 10:24 Comment(0)
S
1

I had the same issue. I think it would be appropriate to check whether your class can be compiled or not. Click recompile (Ctrl+Shift+F9 by default). If its not working then you have to investigate why it isn't compiling.

In my case the code wasn't autocompiling because there were hidden errors with compilation (they weren't shown in logs anywhere and maven clean-install was working). The rootcause was incorrect Project Structure -> Modules configuration, so Intellij Idea wasn't able to build it according to this configuration.

Selection answered 10/2, 2020 at 15:58 Comment(0)
P
0

I was getting error: some jars are not in classpath.So I just delete the corrupted jar and perrform below steps

1.Project >  Setting>Build,Execution,Deployment>Compiler>check build project automatically
2.CTRL+SHIFT+A find/search **registry** --Check for below param
compiler.automake.allow.when.app.running
compiler.automake.trigger.delay=500---According to ur requirement
3.Add devtool in pom.xml
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
4.Build ,If found any probelm while building ,saying some jar in not in class path.Just delete the corrupted jar
and re-build the project angain after sync with maven lib
Panamerican answered 7/5, 2018 at 2:56 Comment(0)
C
-2

Not enough points to comment on an existing answer, but similar to some people above, I wound up just adding a macro & keymap to Organize Imports / Format / SaveAll / FastReload(F9) / Synchronize.

The synchronize is added as it seems to be the only way I can also see updates in resources modified by external build tools / watchers (i.e., webpack).

The process is slower than eclipse - and for the external file refresh often have to run the command multiple times - but suppose I can live with it.

Cowie answered 14/7, 2017 at 2:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.