简体   繁体   中英

Gradle : Could not find or load main class

Here is my tree files:

src
--JaJson.java
build.gradle

Here is my JaJson.java:

public class JaJson {

    public static void main(String args[]) {  
    System.out.println("Hello");  
    }  
    public JaJson(){
        System.out.println("what time is it ?");
    }

    public void getTime(){
        System.out.println("Hammer time!");
    }
}

Here is my gradle.build:

apply plugin: 'java'
apply plugin: 'eclipse'
//apply plugin: 'java-library'
apply plugin: 'application'

mainClassName = "JaJson"
// tag::repositories[]
repositories { 
    mavenCentral() 
}
// end::repositories[]

java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(11)
    }
}


sourceSets {
    single{
        java {
            srcDir 'src'
            
        }
    }
}


jar {
  manifest {
    attributes(
      'Class-Path': configurations.compile.collect { it.getName() }.join(' '),
      'Main-Class': 'JaJson'
    )
  }
}
task compileSingle(type: JavaCompile) {
    source = sourceSets.single.java
    sourceSets.main.java.srcDirs = ['src']
    classpath = sourceSets.main.compileClasspath
    destinationDirectory = sourceSets.main.output.classesDirs[0]

}
compileJava {
    options.release = 7
}



version = '1.2.1'


// tag::dependencies[]
dependencies {
    implementation "joda-time:joda-time:2.2"
    testImplementation "junit:junit:4.12"
}

When i make a gradle build and a:

java -jar build\libs\jajson-1.2.1.jar

It works fine and print hello

But when i try to launch the class only with:

java build\classes\java\main\JaJson.class 

I have a:

Impossible to found or load main class for  build\classes\java\main\JaJson.class 

And before each build i rm the builds folder.

rd /s /q build
gradle build && java -jar build\libs\jajson-1.2.1.jar && java build\classes\java\main\JaJson.class 

regards

Run as

java -cp build/classes/main/java JaJason

As explained in the Java command's help you need to give the name of the main class, not a path to the main class. If your classes don't live in the current directory (or in their package directory right under the current directory), you need to specify the classpath:

--class-path classpath, -classpath classpath, or -cp classpath

[...] If the class path option isn't used and classpath isn't set, then the user class path consists of the current directory (.).

That said, you can also run a simple .java file straight from the command line:

java src/JaJson.java

This is useful to quickly run single-file programs without going through the whole Gradle build cycle.

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