Can you use Java Code as part of a Jenkins Shared Library?

To go more in details, I don’t mean compiling the library and then using the classes, or using a JAR built from the library, or building the library, publishing to maven/gradle and then importing it inside of the Shared Library. I’m wondering if I can use the Java Library source code, directly in the shared library, the same way you can with groovy files. For example in the documentation, in the src directory, they show src/groovy_library (Extending with Shared Libraries), however could I do src/main/java/java_library, and then import + use the java code in the groovy files.

Hello @GelatinousOrangutan and welcome to this community. :wave:

In Jenkins Shared Libraries, the primary language for scripting is Groovy. Shared Libraries allow you to write custom Groovy scripts that can be used in Jenkins pipelines. While you can’t directly include Java source code files in the src directory of a Shared Library like you do with Groovy scripts, you should still be able to use Java classes within your Groovy scripts. Here’s how you could theoretically do it (haven’t tested):

  1. Write Java Code: You can write your Java code as usual, but it will reside in a separate Java project or module, not directly within the Shared Library’s src directory.
  2. Compile Java Code: Compile your Java code into bytecode (.class files) using a Java compiler.
  3. Packaging and JAR File: Package your compiled Java classes into a JAR file. This JAR file should be self-contained and include any dependencies your Java code requires.
  4. Import JAR into Shared Library: Import the JAR file into your Shared Library by placing it in a directory where your Shared Library can access it. This could be a directory relative to your Shared Library’s root directory.
  5. Use Java Classes in Groovy Scripts: In your Groovy scripts within the Shared Library, you can import and use the Java classes from the JAR file as you would with any Java class. Groovy seamlessly integrates with Java so that you can import and use Java classes just like Groovy classes. At least, that’s what I believe. :thinking:

Here’s an example of how you might use Java classes in a Groovy script within your Shared Library:

// Import your Java class
import com.example.MyJavaClass

node {
    stage('Example') {
        // Create an instance of your Java class
        def myJavaObject = new MyJavaClass()

        // Call methods on your Java object
        myJavaObject.doSomething()
    }
}

My $0.02.

Do we have any sample GitHub project for the above example?