Groovy constant

Groovy constant DEFAULT
packagepolitie.jenkinsclassConstants {// Major version number used by all jobs.// Corresponds with the sprint number; update this at the start of each sprint.staticfinalMAJOR_VERSION_NUMBER='1';staticfinalSONAR_URL='enter sonarqube your url here';staticfinalGITLAB_WEB_BASE_URL='enter gitlab url here';staticfinalGITLAB_API_BASE_URL='enter gitlab api url here';staticfinalGITLAB_CHECKOUT_BASE_URL='enter gitlab checkout url here';staticfinalGITLAB_VERSION='8.6';staticfinalGITLAB_CREDENTIALS_ID='enter credentials here';staticfinalGITLAB_API_TOKEN_CREDENTIALS_ID='enter api token here';staticfinalENVIRONMENT_DOMAIN_NAME='.tld'staticfinalENVIRONMENT_TENANT='foobar';}


static final planet = "Earth" static final planet = 'Earth' static final planet = /Earth/ static final planet = '''Earth''' static final planet = """Earth"""
planet : constant String := "Earth";
const char *_planet = "Earth";
(def planet "Earth")
// using char* constexpr char planet[] = "Earth"; // using string const std::string planet{"Earth"};
const string _planet = "Earth";
const string planet = "Earth";
immutable string planet = "Earth";
static immutable string planet = "Earth";
enum string planet = "Earth";
enum planet = "Earth";
const String _planet = "Earth";
Planet = "Earth".
character(*), parameter :: planet = "Earth"
character(len=*), parameter :: planet = "Earth"
const planet = "Earth"
const planet = 'Earth'
static final String planet = "Earth";
(defparameter +planet+ "Earth")
NSString * const [email protected]"Earth";
const PLANET = 'Earth';
define('PLANET', 'Earth');
const planet = 'Earth';
const my $planet => 'Earth';
const PLANET: &str = "Earth";
Const PLANET = "Earth"
  1. Google profile picture ideas
  2. Rgb neon color codes
  3. Honda shadow 600 tires size

Access constant from Groovy class in Gradle buildfile

Ah now I see what you’re trying. ProductVersion is part of your project you’re building which is a gradle plugin and not part of a gradle plugin you use for building your project.

This is currently not out of the box supported, because the classes of the project itself are not part of the build classpath. You have different options here I guess

  1. use regex to get the versionId out of your ProductVersion class
  2. reverse the way the version is handled. you can declare the version in your build script and then prepocess your ProductVersion java file to get this version information backed into this file.
  3. alternatively use a method in ProductVersion to resolve the version from a property file instead of having a field for this. From the user perspective this would look the same as your current user api as you can take advantage from groovy’s property syntax.

personally I would go with option3. A solution could look like this:

You would need an additional properties file where you store the version information:

Now you just need to ensure this version information is updated during the build:

Now you still have the contract of , but the version information is owned by the build process, which is imo the better place for this information.


1 Like

Groovy update: What's new in Groovy 3 and coming in 4 - Paul King

Global constants in Groovy

Groovy doesn't really have a global scope. When you have a groovy script that doesn't declare a class, it implicitly gets stuck in a class with the name of the script. So final variables at the top-level scope are really just fields of the implicit class. For example:

Is more or less equivalent to:

It's easy to see why it doesn't work expanded out. An easy work around is to declare your "globals" in a dummy class called e.g. Constants, and then just do a static import on it. It even works all in a single script. Example:


Also, scripts are bit of a special case. If you declare a variable without or any modifiers such as , (i.e. just use it) it goes into a script-wide binding. So in this case:

CONSTANT is in the script-wide binding, but in:

CONSTANT is a local variable in the script's method. More information on this can be found at the archived link to some Groovy - Scoping and the Semantics of "def" page.

answered Feb 1 '11 at 6:42


61.5k1919 gold badges152152 silver badges184184 bronze badges


Constant groovy

That Groovy Style Guide - Constants

That Groovy Style Guide - Constants

1. Do things in object oriented way
Remember that it is still a language of Object Orientation

2. No simi-colon
Lets do everything in a Groovy way

3. Define constants in a separate class for external access

4. Define a class for constant type instead of primitive types when constant need to have other attributes
Like: deploymentEnvironment: dev, production, testing.

Recently I have been working on finding a way to write a portale Groovy common library for Jenkins pipelines at ThoughtSpot. By portable, I mean writing common functions/utilities that is pure Groovy without using any Jenkins plugin step. It is clear that we will go for this kind of portable Groovy common lib instead of having any dependency Jenkins Plugins step, which is only useful on Jenkins server. After searching/referencing here and there, I finally had a working version of a pure Groovy lib. But, a problem rose in code review phase: what code style should we adopt for native Groovy code in production ? It is crucial that we should write code in best practice so that it is maintainable in the long run. One heated discussion we had for my first version deliverable is about constants. We went for Groovy official style guide, and it was helpful, but it doesn’t include everything as expected. Specifiaclly, we didn’t find a solid official guide on how to structure global constants for reference, internal discussions were subjectively skewed, like we should follow what we did in python, etc. After I spent some time investigating on it, I found many good articles demonstrating a good way to manage constants. Together with my own understanding, I present you: That Groovy Style Guide - Constants as listed above. (‘That’ here to differentiate this from any official documentation)

Lets take an look at a few examples and see how I recommend the style above:

  1. You can always define constants local to a file/class and only use them in that file. Skip that here.

  2. A basic example:

This basic example can help you manage all commonly used primitive constants in one place, but giving access to all places whereever it is imported.

  1. When you need to manage constants in a more complex cases: for different deployment mode(dev, prod, testing), fir different release version, have a constants class like above is no longer manageable, extendable. Here is an example that can address all those needs and provide many other benefits in design:

Here with Constant itself defined as a type, we are able to keep track to: 1) Since which version of lib, such constant is available. 2) Which mode is one constant applied to. It is not possible with simply using primitive types. In addition, using multiple classes/files for different versions and modes my make that happen, but it is neat and manageable in the long run since in competitive markets, products evolve fast, which makes versions and modes change fast.

There are many arguments on above approach is bad. Here, in order to show above design is relatively good, I am addressing all those arguments by list what arguments are and providing my defending opinions.

  1. Defining an object instead of primitives consume more space! Not really. Although they are defined as objects, they are static, and only initialized once, and shared among all places. So, it won’t consume much space because of unnecessary initializations. However, when number of constants grow, it will consume a lot of unecessary space expecially, not every constant is used every time. To address that, lazy initialization can be used when you have a large number of constants in a class. Furthermore, if there is multi-threading, use “double-check” idiom for synchronized inittialization.

  2. It is not straight-forward to use object type as constant value! Not really! Remember it is still an language of object orientation. whenever you need to use an object type, use it. It is true that constant is meant to store values and provide easy access, but dont’t forget that in a lot of cases, you need to know more info about the constant before you can use it, and object type address that need.

  3. Comment below if you find any other concern that is not listed.


Java Tip 67: Lazy instantiation
Groovy Style Guide
Java Object Size Calculations in 64-bit
Groovy Object orientation
Create enumerated constants in Java
Use constant types for safer and cleaner code


There is a catch when we define a constant field in Groovy. Rob Fletcher blogged about this in the post Groovy the public keyword a while ago. When we omit the keyword for a method then the method is still accessible as public method, because Groovy makes the method public when the class is compiled. When we leave out the keyword for fields Groovy creates a getter and setter method for the field at compile time and turns it into a property that applies to the Java Bean specification. This is also true if the field is static. So if we define a constant value as we must keep in mind that Groovy will generate a getter method so the constant value is a read only property according to Java Bean specification.

Let's create a simple class with a constant field , a property and a method. We leave out any keyword:

// File: sample.groovy // Groovy makes class public. class Sample { // Groovy adds getDEFAULT and no setDEFAULT. static final String DEFAULT = 'default' // Groovy adds setMessage/getMessage String message // Groovy makes method public. void message(final String newMessage) { this.message = message } }

If we compile this class we get the following methods and fields (using to inspect the class):

$ javap -p -constants Sample Compiled from "sample.groovy" public class Sample implements groovy.lang.GroovyObject { private static final java.lang.String DEFAULT = "default"; private java.lang.String message; ... public void message(java.lang.String); ... public static final java.lang.String getDEFAULT(); public java.lang.String getMessage(); public void setMessage(java.lang.String); }

If we want to access the constant field in Groovy we can still use , but from Java code this doesn't work. You can see in the generated class file we should invoke , because this method is public. To overcome this we simply add to our constant field definition. This way Groovy will leave the field unchanged and in the generated class file it is still public. Then from Java we can use to access the constant value. Let's see the output of when we make the field public:

$ javap -p -constants Sample Compiled from "sample.groovy" public class Sample implements groovy.lang.GroovyObject { public static final java.lang.String DEFAULT = "default"; private java.lang.String message; ... public void message(java.lang.String); ... public java.lang.String getMessage(); public void setMessage(java.lang.String); }

This also helps an IDE, like IntelliJ IDEA, to do a proper based on the constant field.

Written with Groovy 2.4.4.


You will also like:






  • Modifier and TypeConstant FieldValue






  • Modifier and TypeConstant FieldValue




  • Modifier and TypeConstant FieldValue
  • Modifier and TypeConstant FieldValue

1253 1254 1255 1256 1257