简体   繁体   中英

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:

在此输入图像描述

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)...

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 (ie, 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. 在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM