'Can I include Java constant value in AsciiDoctor document?

For example, lets have a Java constant in some class

public class MyClass{
  public static final String ENDPOINT="http://example.com"
}

and lets try to describe that class in AsciiDoctor (corporate docs reasons)

==== My class

..... some descripton ..... 
It is exposed trough http://example.com

Now every time I change the endpoint, I have to update docs manually as well (IDE find-and-replace will do the trick obviously). Is there a way to include Java constant into the AsciiDoc so I don't have to copy its value into the docs?

I would gladly see something like {import my.package.MyClass#ENDPOINT} or something similiar.



Solution 1:[1]

One other solution is to use the include-pattern of asciidoctor which is described here. https://docs.asciidoctor.org/asciidoc/latest/directives/include-tagged-regions/

In short.

Define a tagged region:

public class MyClass{
  //tag::endpointdefinition[]
  public static final String ENDPOINT="http://example.com"
  //end::endpointdefinition[]
}

include it your document

[source,java]
----
include::pathYourFile.java[tag=endpointdefinition] 
----

To optimize it a little bit you could break your lines different int the java file and place the tag definition on that. You could also remove the source around including the java file.

Solution 2:[2]

I'd write a shell script (PERL, whatever) that greps your Java code for a regex something like 'class (\w+).*ENDPOINT="([^"]+)', sending the results to an include file (./endpoints.adoc) using ':\1_endpoint: \2', thus:

:MyClass_endpoint: http://example.com
:MyOtherClass_endpoint: http://other.example.com

Then, at the top of your AsciiDoc file insert: include::endpoints.adoc[]

and then refer to {MyClass_endpoint} and {MyOtherClass_endpoint} in the body.

Then, simply run the script as part of your toolchain prior to calling AsciiDoctor.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 EhmKah a.k.a. Michael Krauße
Solution 2 eskwayrd