Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run main method using Gradle from within IntelliJ IDEA?

Am new to IntelliJ IDEA (using 2017.1.3) and gradle...

Java file:

package com.example;

public class HelloGradle {

    public static void main(String[] args) {
        System.out.println("Hello Gradle!");
    }
}

build.gradle:

group 'com.example'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'application'

mainClassName = "HelloGradle"

sourceCompatibility = 1.8

repositories {
    maven {
        url("https://plugins.gradle.org/m2/")
    }
}

task(runMain, dependsOn: 'classes', type: JavaExec) {
    main = 'com.example.HelloGradle'
    classpath = sourceSets.main.runtimeClasspath
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

When I click on the run task inside the Gradle Projects window, I get the following:

enter image description here

How can I setup either Gradle or IntelliJ IDEA to print the content in the main method to IntelliJ IDEA's Console view?

Really don't understand why the Console view didn't pop up (from within IntelliJ IDEA and also why it doesn't show me what the error is)...

like image 806
PacificNW_Lover Avatar asked Dec 10 '22 11:12

PacificNW_Lover


1 Answers

To set up IntelliJ to run your main class all you have to do is to right-click the main() method in your HelloGradle class, then choose "Run HelloGradle.main()" from the menu. You only do this once, because it will now show up on the top-right Run/Configuration menu together with other tasks (i.e., Gradle tasks) you run. Output should display in your console now.

For you gradle file, this is all you need to get all the Gradle tasks under Tasks->build->... running smoothly.

group 'com.example'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
   mavenCentral()
}
dependencies {
   testCompile group: 'junit', name: 'junit', version: '4.12'
}
task(runMain, dependsOn: 'classes', type: JavaExec) {
   main = 'com.example.HelloGradle'
   classpath = sourceSets.main.runtimeClasspath
}

Just in case, don't forget to hit the "refresh" button, the top-left one in the Gradle projects view.

UPDATE1: I added the task portion in the Gradle file and it runs fine. You can run the project from the Gradle project->Run Configurations->HelloGradle[runMain]. To see the output, there is a toggle-button in the Run view at the bottom-left, it's called "Toggle tasks execution/text mode" with an "ab" icon on it; push it and you should see the output just the same.

UPDATE2: Click the encircled button to see output.enter image description here

like image 113
mohsenmadi Avatar answered Dec 12 '22 23:12

mohsenmadi