如何从Gradle调用静态Java方法

如何从Gradle调用静态Java方法

本文介绍了如何从Gradle调用静态Java方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个gradle构建脚本,该脚本当前可以通过简单地通过其main方法执行Java类来工作。我想知道的是,如何在同一个类中调用静态方法,而不必遍历main方法。当前的gradle代码如下:

I have a gradle build script which currently works by simply executing a Java class through it's main method. 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. The current gradle code is as follows:

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'
}

我的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);
    }
}

这给了我输出:

: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

我的问题很简单,我如何才能跳过主要方法,而直接从gradle脚本中调用方法 anotherMethod?输出将简单地为:

My question is simply how can I skip the main method, and call the method "anotherMethod" directly from the gradle script? The output would then simply be:

In anotherMethod
arg1 arg2

谢谢

推荐答案

您必须添加罐子或类到类路径。这是一个包含该类的jar文件的示例。
在文件build.gradle内添加依赖项。
我的jar文件位于 lib 文件夹中,路径为 lib / MQMonitor.jar

you have to add the jar or class to the classpath. here is an example with a jar file who contains the class.Inside the file build.gradle add the dependencies.My jar file is in the lib folder the path is lib/MQMonitor.jar.

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

task myTaskCallJava << {
   MyClass.foo()
}

这篇关于如何从Gradle调用静态Java方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:43