简体   繁体   English

如何从Gradle调用静态Java方法

[英]How do I call a static Java method from Gradle

I have a gradle build script which currently works by simply executing a Java class through it's main method. 我有一个gradle构建脚本,当前可以通过简单地通过它的main方法执行Java类来工作。 What I want to know is, how can I call a static method in the same class but not have to go through the main method. 我想知道的是,如何在同一个类中调用静态方法,而不必遍历main方法。 The current gradle code is as follows: 当前的gradle代码如下:

import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'java'

defaultTasks 'runSimple'

project.ext.set("artifactId", "test-java")

File rootDir = project.getProjectDir()
File targetDir = file("${rootDir}/target")
FileCollection javaClasspath = files("${targetDir}/tools.jar")

task(runSimple, dependsOn: 'classes', type: JavaExec) {
    main = 'com.test.model.JavaTest'
    classpath = javaClasspath
    args 'arg1'
    args 'arg2'
}

And my Java class as follows: 而我的Java类如下:

package com.test.model;

public class JavaTest {

    public static void main(String[] args) throws Exception {
        System.out.println("In main");
        anotherMethod(args[0], args[1]);
    }

    public static void anotherMethod(String arg1, String arg2) {
        System.out.println("In anotherMethod");
        System.out.println(arg1 + " " + arg2);
    }
}

This gives me the output: 这给了我输出:

:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:runSimple
In main
In anotherMethod
arg1 arg2

BUILD SUCCESSFUL

Total time: 2.344 secs

My question is simply how can I skip the main method, and call the method "anotherMethod" directly from the gradle script? 我的问题只是简单地如何跳过main方法,而直接从gradle脚本中调用方法“ anotherMethod”? The output would then simply be: 输出将简单地是:

In anotherMethod
arg1 arg2

Thanks 谢谢

you have to add the jar or class to the classpath. 您必须将jar或类添加到类路径。 here is an example with a jar file who contains the class. 这是一个包含该类的jar文件的示例。 Inside the file build.gradle add the dependencies. 在文件build.gradle内添加依赖项。 My jar file is in the lib folder the path is lib/MQMonitor.jar . 我的jar文件位于lib文件夹中,路径为lib/MQMonitor.jar

import mypackage.MyClass
buildscript {
   repositories {
      flatDir name: 'localRepository', dirs: 'lib'
   }
    dependencies {
        classpath name: 'MQMonitor'
    }
}

task myTaskCallJava << {
   MyClass.foo()
}

I have been working on this too. 我也一直在努力。 You know I like the function of eclipse and intellij with the run with Junit options, and I want to do this using command line and gradle. 您知道我喜欢通过Junit选项运行eclipse和intellij的功能,我想使用命令行和gradle进行此操作。

If you could accept putting your test method in the directory of 'test' directory of gradle. 如果您可以接受将您的测试方法放在gradle的“ test”目录中。 I actually have a fair solution. 我实际上有一个公平的解决方案。

package com.udacity.gradle;
import org.junit.Test;

    public class TestClass {
        @Test
        public void anotherMethod() {
            System.out.println("This is it, I want this!!!");
        }
        @Test
        public void notMyWantedMethod1() {

            System.out.println("not my wanted");
        }

        public void notMyWantedMethod2() {
            System.out.println("not my wanted");
        }

    }

This my test class which is in src/test/java/com/udacity/gradle/TestClass.java 这是我的测试类,位于src / test / java / com / udacity / gradle / TestClass.java中

Then the under below is the file of my build.gradle 然后下面的是我的build.gradle的文件

apply plugin: "java"
repositories {
    mavenCentral()
}
dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
}


test {
    testLogging.showStandardStreams = true
    filter {
        //include specific method in any of the tests
        includeTestsMatching "*.TestClass.anotherMethod"
    }
}

Simple idea you know this is a test class so I use the test task of gradle. 一个简单的想法,您知道这是一个测试类,因此我使用gradle的测试任务。 And to specify which method to use, I added a Test filter which could specify down to method. 为了指定要使用的方法,我添加了一个测试过滤器,可以指定方法。

Then you could just run 那你就可以跑

gradle test

Then you could find in console that you have what you want in there. 然后,您可以在控制台中找到所需的内容。 However, remember to add 但是,请记住添加

testLogging.showStandardStreams = true

if you don't do this, gradle would swallow your console output. 如果您不这样做,gradle将吞噬您的控制台输出。 But even if you don't add this line. 但是,即使您不添加此行。 You could read a test log in the directory of 您可以在以下目录中阅读测试日志

...../build/test-results/test/TEST-com.udacity.gradle.TestClass.xml ..... / build / test-results / test / TEST-com.udacity.gradle.TestClass.xml

There are well organized test reports output in it. 其中有组织良好的测试报告输出。

<?xml version="1.0" encoding="UTF-8"?>
<testsuite name="com.udacity.gradle.TestClass" tests="1" skipped="0" failures="0" errors="0" timestamp="2018-03-31T19:26:44" hostname="hexin-PC" time="0.022">
  <properties/>
  <testcase name="anotherMethod" classname="com.udacity.gradle.TestClass" time="0.022"/>
  <system-out><![CDATA[This is it, I want this!!!
]]></system-out>
  <system-err><![CDATA[]]></system-err>
</testsuite>

If you want to execute a static method you will need to add the class to the Gradle build script's classpath. 如果要执行静态方法,则需要将类添加到Gradle构建脚本的类路径中。

To add the code to the build scripts classpath if your code is in a repository: 要将代码添加到构建脚本的类路径中(如果代码位于存储库中):

buildscript {
    repositories {
        maven { url "${yourRepositoryURL}" }
    }
    dependencies {
        classpath 'com.yourgroup:yourpackagename:version'
    }
}

To add the code to the build scripts classpath if you code is built locally (I didn't test this one): 如果您的代码是本地构建的,则将代码添加到构建脚本的类路径中(我没有测试这一步):

buildscript {
    dependencies {
        classpath files("path/to/where/the/class/files/are")
    }
}

Then you should be able to call that method just like any other: 然后,您应该能够像其他方法一样调用该方法:

task runSimple(dependsOn: 'classes') {
    doFirst() {
        com.test.model.JavaTest.anotherMethod('arg1', 'arg2')
    }
}

Assuming the class is on the buildscript classpath (it should be, since you're calling main from the same class) 假设该类位于buildscript类路径上(应该是,因为您要从同一类调用main

task runSimple {
  doLast {
    com.test.model.JavaTest.anotherMethod("foo", "bar")
  }
}

Tested on Gradle 4.6 在Gradle 4.6上测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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