Class finder

It’s help to find in project classes that match some criteria.

Find test classes in a package

Source code to find classes containing tests
List<Class<?>> classes = new ClassFinder().classesWithAnnotatedMethod(
        com.github.docastest.doctesting.sample.SimpleClass.class.getPackage(),
        Test.class);

Classes found:

  • com.github.docastest.doctesting.sample.basic.FirstTest

  • com.github.docastest.doctesting.sample.basic.SecondTest

Find test classes in a package with a filter

By default, all classes containing a test method are found. It’s possible to exclude some test methods because they are not relevant in the context. If all test methods of a class are excluded, then the class will not be return as a found class.

Here, we exclude all method in a class with name starting by 'Second'. .Source code to find classes containing tests

List<Class<?>> classes = new ClassFinder().classesWithAnnotatedMethod(
        com.github.docastest.doctesting.sample.SimpleClass.class.getPackage(),
        Test.class,
        m -> !m.getDeclaringClass().getSimpleName().startsWith("Second"));

Classes found:

  • com.github.docastest.doctesting.sample.basic.FirstTest

Find root class from enclosing class

Class used
class FirstClass {
    class SecondClass {
        class ThirdClass {

        }
    }
}
Code to find root class from an enclosing class
final ClassFinder finder = new ClassFinder();
Class<?> clazz = finder.getMainFileClass(FirstClass.SecondClass.ThirdClass.class);
Result
FirstClass

CodeExtractor

It is often useful to retrieve information from the source code itself. This class provides utilities to extract pieces of code or comments.

Extract code

Extract code of a class

How to extract code of a class
Class<?> classToExtract = SimpleClass.class;
String code = CodeExtractor.classSource(classToExtract);
Source code to extract
package com.github.docastest.doctesting.sample;

public class SimpleClass {
    public int simpleMethod() {
        return 0;
    }
}
Source code extracted
public class SimpleClass {
    public int simpleMethod() {
        return 0;
    }
}

Extract code of an inner class

How to extract code of an inner class
String code = CodeExtractor.classSource(CodeExtractorTest.SimpleInnerClass.class);
Source code to extract
class SimpleInnerClass {
    public int simpleMethod() {
        return 0;
    }
}
Source code extracted
class SimpleInnerClass {
    public int simpleMethod() {
        return 0;
    }
}

Extract code of a non public class in file

It’s not possible to extract code of a non public class because it’s not possible to determine source file. To be able to extract it, we have to explicitly give source file.

How to extract code of a non public class
String code = CodeExtractor.classSource(CodeExtractorTest.class,
        ClassNestedWithCommentToExtract.SubClassNestedWithCommentToExtract.class);
Source code to extract
/**
 * Comment of the class.
 */
@NotIncludeToDoc
class ClassNestedWithCommentToExtract {

    /**
     * Comment of the subclass.
     */
    class SubClassNestedWithCommentToExtract {
        /**
         * Method comment in an inner class.
         */
        @Test
        public void methodInSubClass() {
            System.out.println("My method");
        }
    }
}
Source code extracted
/**
 * Comment of the subclass.
 */
class SubClassNestedWithCommentToExtract {
    /**
     * Method comment in an inner class.
     */
    @Test
    public void methodInSubClass() {
        System.out.println("My method");
    }
}

Non public class in a file could not be retrieve without giving main class of the file containing searching class.

This code does not work and throw an exception
String code = CodeExtractor.classSource(
        ClassNestedWithCommentToExtract.SubClassNestedWithCommentToExtract.class);
Example 1. Exception thrown
java.nio.file.NoSuchFileException: src/main/java/com/github/docastest/codeextraction/ClassNestedWithCommentToExtract.java

Extract code of a an enum in file

How to extract code of an enum
String code = CodeExtractor.enumSource(EnumWithCommentToExtract.MyEnum.class);
Source code to extract
/**
 * Comment of the class.
 */
public class EnumWithCommentToExtract {

    /**
     * Comment of the enum.
     */
    public static enum MyEnum {
        /**
         * First enum with comment.
         */
        FirstEnum,
        /** Second enum with comment. */
        SecondEnum,
        ThirdEnum;

        /**
         * A method in enum.
         */
        public void methodInEnum() {

        }
    }

}
Source code extracted
/**
 * Comment of the enum.
 */
public static enum MyEnum {
    /**
     * First enum with comment.
     */
    FirstEnum,
    /** Second enum with comment. */
    SecondEnum,
    ThirdEnum;

    /**
     * A method in enum.
     */
    public void methodInEnum() {

    }
}
How to extract code of an enum declared outside the class
String code = CodeExtractor.enumSource(CodeExtractorTest.class,
        EnumNotInAClass.class);
Source code to extract
enum EnumNotInAClass {
    First,
    Second
}
Source code extracted
enum EnumNotInAClass {
    First,
    Second
}
How to extract code of an enum declared in a class not in his file
String code = CodeExtractor.enumSource(CodeExtractorTest.class,
        ClassWithEnum.EnumInAClass.class);
Source code to extract
class ClassWithEnum {
    enum EnumInAClass {
        First,
        Second
    }
}
Source code extracted
enum EnumInAClass {
    First,
    Second
}

Extract code from method

Method source code can be retrived from his method object or from his class and his method name. It’s also possible to retrieve only the method body.

How to extract code of a method
String code = CodeExtractor.methodSource(SimpleClass.class, "simpleMethod");

or

Method method = MethodReference.getMethod(SimpleClass::simpleMethod);
String code = CodeExtractor.methodSource(method);
Source code from file
public class SimpleClass {
    public int simpleMethod() {
        return 0;
    }
}
Source code extracted
public int simpleMethod() {
    return 0;
}

We could not extract method source when there is two methods with same name in the class. .Extract code of a method with several signatures

String code = CodeExtractor.methodSource(DuplicateMethodClass.class, "duplicateMethod");

java.lang.RuntimeException: More than one method with name 'duplicateMethod'

How to extract code of a method in a nested class
Method method = MethodReference.getMethod(ClassWithNestedClass.NestedClass::nestedMethod);
String code = CodeExtractor.methodSource(method);
Source code from file
public class ClassWithNestedClass {
    public int simpleMethod() {
        return 0;
    }

    public class NestedClass {
        public int nestedMethod() { return 2; }
    }
}
Source code extracted
public int nestedMethod() { return 2; }
How to extract body of a method
String code = CodeExtractor.extractMethodBody(SimpleClass.class, "simpleMethod");
Source code from file
public class SimpleClass {
    public int simpleMethod() {
        return 0;
    }
}
Source code extracted
return 0;

Extract a part of code from method

To extract a part of a method, you can write a comment with a specific value that indicate beginining of the code to extract. Another comment with a specific value indicate the end of the code.

How to extract part of a method code
Method method = MethodReference.getMethod(ClassWithMethodToExtract::methodWithOnePartToExtract);
String code = CodeExtractor.extractPartOfMethod(method);

or

String code = CodeExtractor.extractPartOfMethod(ClassWithMethodToExtract.class, "methodWithOnePartToExtract");
Source code from file
public void methodWithOnePartToExtract() {
    int i = 0;
    // >>>
    int j = i;
    // <<<
    int k = i + j;
}
Source code extracted
int j = i;

You can have several part identify by a text that you pass as argument to the function extracting the code. You can have several part identified by the same text. In that case, all parts matching the text will be returned.

How to extract part of a method
Method method = MethodReference.getMethod(ClassWithMethodToExtract::methodWithSeveralPartsToExtract);
String codePart1 = CodeExtractor.extractPartOfMethod(method, "Part1");
String codePart2 = CodeExtractor.extractPartOfMethod(method, "Part2");
Source code from file
public int methodWithSeveralPartsToExtract(int value) {
    // >>>Part1
    int square = value * value;
    // <<<Part1

    // >>>Part2
    final String text = String.format(
            "square(%d)=%d",
            value,
            square);
    System.out.println(text);
    // <<<Part2

    // >>>Part1
    return square;
    // <<<Part1
}
Source code Part 1 extracted
int square = value * value;
return square;
Source code Part 2 extracted
final String text = String.format(
        "square(%d)=%d",
        value,
        square);
System.out.println(text);

Extract a part of code from a file

How to extract part of a method code
String code = CodeExtractor.extractPartOfFile(path, "import");
File content
package com.github.docastest.doctesting.sample;

// >>>import
import static java.lang.Math.*;
// <<<import

public class FileWithCodeToExtract {

    public int absoluteValue(int value) {
        return abs(value);
    }
}
Content extracted
import static java.lang.Math.*;

Extract a part of code from the current method

How to extract code from the current method
String code = CodeExtractor.extractPartOfCurrentMethod();
Source code from file
public String method_with_code_to_extract() {
    // >>>
    String value = "some text";
    // <<<

    return CodeExtractor.extractPartOfCurrentMethod();
}
Source code extracted from the current method
String value = "some text";
How to extract code from the current method using a tag
String code = CodeExtractor.extractPartOfCurrentMethod("2");
Source code from file
public String method_with_code_to_extract_with_tag() {
    // >>>1
    String value1 = "some text";
    // <<<1

    // >>>2
    String value2 = "code to extract";
    // <<<2

    return CodeExtractor.extractPartOfCurrentMethod("2");
}
Source code extracted from the current method
String value2 = "code to extract";

Extract part of code

We shows here some technical cases.

Tag with same beginning of another tag

Tag (MyCode) could be a subpart of another one (MyCodeBefore or MyCodeAfter).

Source code with extractor tags
// >>>MyCodeBefore
String partBefore = "Part before MyCode";
// <<<MyCodeBefore

// >>>MyCode
String partMyCode = "Part MyCode";
// <<<MyCode

// >>>MyCodeAfter
String partAfter = "Part after MyCode";
// <<<MyCodeAfter
Source code part MyCodeBefore extracted
String partBefore = "Part before MyCode";
Source code part MyCodeAfter extracted
String partAfter = "Part after MyCode";
Source code part MyCode extracted
String partMyCode = "Part MyCode";
Tag beginning with same outer tag name

Tag inside another one can be a subpart (MyCode) of the global one (MyCodeGlobal) .

Source code with extractor tags
// >>>MyCodeGlobal
String partGlobalBefore = "Part global before MyCode";

// >>>MyCode
String partMyCode = "Part MyCode";
// <<<MyCode

String partGlobalAfter = "Part global after MyCode";
// <<<MyCodeGlobal
Source code part MyCodeInside extracted
String partMyCode = "Part MyCode";
Source code part MyCodeInsideAround extracted
String partGlobalBefore = "Part global before MyCode";

// >>>MyCode
String partMyCode = "Part MyCode";
// <<<MyCode

String partGlobalAfter = "Part global after MyCode";
Tag beginning with same inner tag name

Tag inside (MyCodeGlobalInside) another one can be an extension of an outside tag (MyCodeGlobal).

Source code with extractor tags
// >>>MyCodeGlobal
String partGlobalBefore = "Part global before MyCode";

// >>>MyCodeGlobalInside
String partInside = "Part MyCode";
// <<<MyCodeGlobalInside

String partGlobalAfter = "Part global after MyCode";
// <<<MyCodeGlobal
Source code part MyCodeEnclosed extracted
String partInside = "Part MyCode";
Source code part MyCodeEnclosedInside extracted
String partGlobalBefore = "Part global before MyCode";

// >>>MyCodeGlobalInside
String partInside = "Part MyCode";
// <<<MyCodeGlobalInside

String partGlobalAfter = "Part global after MyCode";

Extract comment

Extract class comment

How to extract comment of a class
final String comment = CodeExtractor.getComment(ClassWithCommentToExtract.class).orElse("");
/**
 * Comment of the class.
 */
public class ClassWithCommentToExtract {

    /**
     * Comment of the method without parameters.
     */
    public void methodWithoutParameters() {

    }

    /**
     * Comment of the method with two parameters.
     */
    public void methodWithParameters(int id, String name) {

    }

}
Comment extracted from class
Comment of the class.
How to extract comment of a nested class
final String comment = CodeExtractor.getComment(CodeExtractorTest.NestedClass.class).orElse("");
/**
 * Comment of the nested class of CodeExtractorTest.
 */
@NotIncludeToDoc
class NestedClass {
    /**
     * Method comment in an inner class.
     */
    @Test
    public void methodInSubClass() {
        System.out.println("My method");
    }
}
Comment extracted from class
Comment of the nested class of CodeExtractorTest.
How to extract comment of class that is not the main class of his file.
final String comment = CodeExtractor.getComment(CodeExtractorTest.class, ClassNestedWithCommentToExtract.class).orElse("");
/**
 * Comment of the class.
 */
@NotIncludeToDoc
class ClassNestedWithCommentToExtract {

    /**
     * Comment of the subclass.
     */
    class SubClassNestedWithCommentToExtract {
        /**
         * Method comment in an inner class.
         */
        @Test
        public void methodInSubClass() {
            System.out.println("My method");
        }
    }
}
Comment extracted from class
Comment of the class.

Extract method comment

/**
 * Comment of the class.
 */
public class ClassWithCommentToExtract {

    /**
     * Comment of the method without parameters.
     */
    public void methodWithoutParameters() {

    }

    /**
     * Comment of the method with two parameters.
     */
    public void methodWithParameters(int id, String name) {

    }

}

How to extract comment of a method

final Method method = ClassWithCommentToExtract.class.getDeclaredMethod("methodWithoutParameters");
final Optional<String> comment = CodeExtractor.getComment(
        ClassWithCommentToExtract.class,
        method
);
From method without arguments.
Comment of the method without parameters.

How to extract comment of a method with parameters

final Method method = ClassWithCommentToExtract.class.getDeclaredMethod("methodWithParameters", int.class, String.class);
final Optional<String> comment = CodeExtractor.getComment(
        ClassWithCommentToExtract.class,
        method
);
From method with parameters.
Comment of the method with two parameters.

How to extract comment of a method using Method object

final Method methodWithComment = ClassWithCommentToExtract.class.getMethod("methodWithoutParameters");
final Optional<String> comment = CodeExtractor.getComment(methodWithComment);
From method
Comment of the method without parameters.

How to extract comment of a method with parameters using Method object

final Method methodWithComment = ClassWithCommentToExtract.class.getMethod("methodWithParameters", int.class, String.class);
final Optional<String> comment = CodeExtractor.getComment(methodWithComment);
From method
Comment of the method with two parameters.

How to extract comment of a method of an inner class

final Method methodWithComment = MethodReference.getMethod(ClassNestedWithCommentToExtract.SubClassNestedWithCommentToExtract::methodInSubClass);
final Optional<String> comment = CodeExtractor.getComment(this.getClass(), methodWithComment);
From method
Method comment in an inner class.

Extract field comment

public class FieldWithCommentToExtract {
    /**
     * Comment on a public field.
     */
    public String publicField;

    /**
     * Comment on a private field.
     */
    private String privateField;

    private String fieldWithoutComment;

    public static class SubClassWithFieldToExtract {
        /**
         * Comment on a subclass field.
         */
        public String subclassField;
    }

}

It is not possible to have a reference to a field. You have to retrieve the field through a string.

Code to extract the comment from a public field
Optional<String> comment = CodeExtractor.getComment(
        FieldWithCommentToExtract.class.getDeclaredField("publicField")
);

Comment extracted: Comment on a public field.

Code to extract the comment from a private field
Optional<String> comment = CodeExtractor.getComment(
        FieldWithCommentToExtract.class.getDeclaredField("privateField")
);

Comment extracted: Comment on a private field.

Code that attempts to extract a comment from a field that does not have one
final Optional<String> comment = CodeExtractor.getComment(
        FieldWithCommentToExtract.class.getDeclaredField("fieldWithoutComment")
);

Comment extracted: Empty Optional

Code that attempts to extract a comment from a field in a subclass
final Optional<String> comment = CodeExtractor.getComment(
        FieldWithCommentToExtract.SubClassWithFieldToExtract.class.getDeclaredField("subclassField")
);

Comment extracted: Comment on a subclass field.

Extract enum comment

/**
 * Comment of the class.
 */
public class EnumWithCommentToExtract {

    /**
     * Comment of the enum.
     */
    public static enum MyEnum {
        /**
         * First enum with comment.
         */
        FirstEnum,
        /** Second enum with comment. */
        SecondEnum,
        ThirdEnum;

        /**
         * A method in enum.
         */
        public void methodInEnum() {

        }
    }

}

How to extract comment of an enum

final String comment = CodeExtractor.getComment(
        EnumWithCommentToExtract.class,
        EnumWithCommentToExtract.MyEnum.class
).orElse("");

Comment extracted: Comment of the enum.

How to extract comment of one value of an enum

final Optional<String> comment = CodeExtractor.getComment(
        EnumWithCommentToExtract.class,
        EnumWithCommentToExtract.MyEnum.FirstEnum
);

Comment extracted: First enum with comment.

How to extract comment of one value of an enum

final Optional<String> comment = CodeExtractor.getComment(
        EnumWithCommentToExtract.MyEnum.SecondEnum
);

Comment extracted: Second enum with comment.

How to extract comment of one value of an enum

final Optional<String> comment = CodeExtractor.getComment(
        EnumWithCommentToExtract.class,
        EnumWithCommentToExtract.MyEnum.ThirdEnum
);

Comment extracted: No comment

Issue: comment not retrieve when an annotation is before the comment

When there is an annotation before the class comment, the comment is not retrieve. This is an issue in the JavaParser we used (com.github.javaparser:javaparser-core:3.22.1).

How to extract comment of a class
final String comment = CodeExtractor.getComment(ClassWithAnnotationBeforeComment.class).orElse("");
@NotIncludeToDoc
/**
 * Comment of the class.
 */
class ClassWithAnnotationBeforeComment {
    // ...
}
Comment extracted from class

Extract code and result

Show extract parameters code

We can use the following code to get values and the code used to obtain it

final List<String> codes = CodeExtractor.extractParametersCode(
        "abcd".substring(2),
        "abcd".substring(2, 4)
);

Result is

"abcd".substring(2)
"abcd".substring(2, 4)

Extract parameters code keep format

We can use the following code to get values and the code used to obtain it

final List<String> codes = CodeExtractor.extractParametersCodeAsItWrite(
        "abcd"
                .substring(2),
        "abcd"
                .substring(2, 4)
);

Result is

"abcd"
        .substring(2)
"abcd"
        .substring(2, 4)

Show extract parameters code from nested class

We can use the following code to get values and the code used to obtain it

static class NestedClassWithArgumentsToExtract {
    public List<String> getCodeExtracted() {
        final List<String> codes = CodeExtractor.extractParametersCode(
                "xyzxxx".substring(2),
                "xyzxxx".substring(2, 4)
        );

        return codes;
    }
}

Result is

"xyzxxx".substring(2)
"xyzxxx".substring(2, 4)

Show extract parameters code with an intermediate method

We can defined a method and retrieve code used as parameters.

public List<String> myMethod(String value_A, String value_B) {
    return CodeExtractor.extractParametersCodeFromStackDepth(2);
}

We can use the method and get values and the code used to obtain it

final List<String> codes = myMethod(
        "abcd".substring(2),
        "abcd".substring(2, 4)
);

Result is

"abcd".substring(2)
"abcd".substring(2, 4)

Show extract parameters code with an intermediate class

We can defined a class and retrieve code used as parameters calling constructor.

public class MyClass {

    private final List<String> parameterCodes;

    MyClass(String value_1, String value_B) {
        parameterCodes = CodeExtractor.extractParametersCodeFromStackDepth(2);
    }
}

We can create an object and get values and the code used calling the constructor.

final List<String> codes = new MyClass(
        "abcd".substring(2),
        "abcd".substring(2, 4)
).parameterCodes;

Result is

"abcd".substring(2)
"abcd".substring(2, 4)

Code path test

Path from a package

Code
final Class<?> clazz = com.github.docastest.samples.MyTest.class;
final Path path = CodePath.toPath(clazz.getPackage());
final String pathText = DocPath.toAsciiDoc(path);

Result

com/github/docastest/samples

Path from a class

Code
final Class<?> clazz = com.github.docastest.samples.MyTest.class;
final Path path = CodePath.toPath(clazz);
final String pathText = DocPath.toAsciiDoc(path);

Result

com/github/docastest/samples/MyTest.java

Path from a nested class

Code
final Class<?> clazz = com.github.docastest.samples.MyTestWithNestedClass.MyNestedClass.class;
final Path path = CodePath.toPath(clazz);
final String pathText = DocPath.toAsciiDoc(path);

Result

com/github/docastest/samples/MyTestWithNestedClass.java

File of a class

Code
final Class<?> clazz = com.github.docastest.samples.MyTest.class;
final Path path = CodePath.toFile(clazz);
final String pathText = DocPath.toAsciiDoc(path);

Result

MyTest.java

File of a nested class

With a nested class, the file is that of the main class of the file.

Code
final Class<?> clazz = com.github.docastest.samples.MyTestWithNestedClass.MyNestedClass.class;
final Path path = CodePath.toFile(clazz);
final String pathText = DocPath.toAsciiDoc(path);

Result

MyTestWithNestedClass.java

Extract information from method reference

MethodReferenceTest class provides tools to extract information from a method reference. It retrieves the method associated with the method reference, so it’s possible to get name. This allows to use the method reference instead of writing the method name as a string. Using refactoring tools, names are automatically updated and there is no risk to misspelled a name.

Find method name

It’s possible to extract method name from a method reference. We can use either a reference using class or using an object instance (only on non-static method).

Code Type Returned value
MethodReference.getName(MyClass::myMethod)

String

myMethod

MethodReference.getName(myObject::myMethod)

String

myMethod

MethodReference.getName(MyClass::myConsumer)

String

myConsumer

MethodReference.getName(MyClass::myFunction)

String

myFunction

MethodReference.getName(myObject::myFunction)

String

myFunction

MethodReference.getName(MyClass::myFunctionWithGeneric)

String

myFunctionWithGeneric

MethodReference.getName(MyClass::myStaticConsumer)

String

myStaticConsumer

Find method

It’s possible to extract method from a method reference.

Code Type Returned value
MethodReference.getMethod(MyClass::myMethod)

Method

public void MyClass.myMethod( )
MethodReference.getMethod(myObject::myMethod)

Method

public void MyClass.myMethod( )
MethodReference.getMethod(MyClass::myConsumer)

Method

public void MyClass.myConsumer( java.lang.String)
MethodReference.getMethod(MyClass::myFunction)

Method

public java.lang.String MyClass.myFunction( java.lang.Integer)
MethodReference.getMethod(myObject::myFunction)

Method

public java.lang.String MyClass.myFunction( java.lang.Integer)
MethodReference.getMethod(MyClass::myFunctionWithGeneric)

Method

public java.util.List MyClass.myFunctionWithGeneric( java.util.List)
MethodReference.getMethod(MyClass::myStaticConsumer)

Method

public static void MyClass.myStaticConsumer( java.lang.String)

Find method name from a specific method

MethodReference class provides some common interface declarations so you can use it with simple methods. When you have a method with several parameters, you need to create your own interface. Those methods could not work with ambiguous method reference (same method name with different parameters).

Specific interface to create
interface MySpecificInterface extends Serializable {
    String apply(Integer param1, String param2, List<String> param3);
}
Code Type Returned value
MethodReference.getName((MySpecificInterface) this::mySpecificMethod)

String

mySpecificMethod

MethodReference.getMethod((MySpecificInterface) this::mySpecificMethod)

Method

public java.lang.String MethodReferenceTest.mySpecificMethod( java.lang.Integer, java.lang.String, java.util.List)

Class used in examples

Class used for the examples
static class MyClass {
    public void myMethod() {
    }

    public void myConsumer(String parameter) {
    }

    public String myFunction(Integer parameter) {
        return null;
    }

    public List<String> myFunctionWithGeneric(List<Integer> parameter) {
        return null;
    }

    public static void myStaticConsumer(String parameter) {
    }

    public String mySpecificMethod(Integer param1, String param2, List<String> param3) {
        return null;
    }
}

ParsedClassRepository

Extract information from source code.

Extraction from method is a naive implementation. We compare only class name without checking the scope (package).

Context

Exemples of this chapter use the following class .Class from which information is extracted

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package com.github.docastest.codeextraction;

import java.util.List;

/**
 * My comment for ClassWithInformationToExtract.
 */
class ClassWithInformationToExtract {

    /**
     * A simple field.
     */
    String aField;

    /**
     * Description of the method 'doSomething'.
     */
    public void doSomething() {
    }

    /**
     * Do something with a String.
     */
    public void doSomething(String param) {
    }

    /**
     * Do something with a java.lang.Character.
     */
    public void doSomething(java.lang.Character param) {
    }

    /**
     * Do something with a List<String>.
     */
    public void doSomething(List<String> param) {
    }

    /**
     * Do something with a String[].
     */
    public void doSomething(String[] param) {
    }

    /**
     * Do something with an Integer.
     */
    public void doSomething(int param) {
    }

    static public class SubClass {
        /**
         * A field in a subclass.
         */
        String subclassField;

    }
}

Retrieve comment

Retrieve comment of a class

How to extract comment
String comment = parser.getComment(ClassWithInformationToExtract.class);
Comment extracted
My comment for ClassWithInformationToExtract.

Retrieve comment of a method

How to extract comment
Method method = ClassWithInformationToExtract.class
        .getMethod("doSomething");
String comment = parser.getComment(method);
Comment extracted
Description of the method 'doSomething'.

Retrieve comment of local class defined in a method

We are not able to deal with local classes(those defined in method).

How to extract comment
/**
 * Comment of local class defined in method.
 */
class MyLocalClass {
    public void doSomething() {

    }
}
String comment = parser.getComment(MyLocalClass.class);
Exception
java.lang.RuntimeException: Local classes are not handled

Retrieve comment of a method with parameter

How to extract comment
Method method = ClassWithInformationToExtract.class
        .getMethod("doSomething", String.class);
String comment = parser.getComment(method);
Comment extracted
Do something with a String.

Retrieve comment of a method with parameter with scope

How to extract comment
Method method = ClassWithInformationToExtract.class
        .getMethod("doSomething", Character.class);
String comment = parser.getComment(method);
Comment extracted
Do something with a java.lang.Character.

Retrieve comment of a method with list parameter

How to extract comment
Method method = ClassWithInformationToExtract.class
        .getMethod("doSomething", List.class);
String comment = parser.getComment(method);
Comment extracted
Do something with a List<String>.

Retrieve comment of a method with array parameter

How to extract comment
Method method = ClassWithInformationToExtract.class
        .getMethod("doSomething", String[].class);
String comment = parser.getComment(method);
Comment extracted
Do something with a String[].

Retrieve line number

Retrieve line of a class

How to get the first line of a class
final int lineNumber = parser.getLineNumber(ClassWithInformationToExtract.class);

Line found: 8

Retrieve line of a method

How to get the first line of a method
Method method = ClassWithInformationToExtract.class.getMethod("doSomething");
int lineNumber = parser.getLineNumber(method);

Line found: 18

Retrieve line of a field

How to get the declaration line of a field
Field field = ClassWithInformationToExtract.class.getDeclaredField("aField");
int lineNumber = parser.getLineNumber(field);

Line found: 13

Retrieve line of a subclass field

How to get the declaration line of a subclass field
Field field = ClassWithInformationToExtract.SubClass.class.getDeclaredField("subclassField");
int lineNumber = parser.getLineNumber(field);

Line found: 55

Retrieve line of an enum

How to get the first line of an enum in a class
final int lineNumber = parser.getLineNumber(EnumWithCommentToExtract.MyEnum.class);

Line found: 11

Retrieve line of a method in an enum

How to get the first line of a method in an enum
Method method = EnumWithCommentToExtract.MyEnum.class.getMethod("methodInEnum");
final int lineNumber = parser.getLineNumber(method);

Line found: 23

Create ParsedClassRepository

We can build a ParsedClassRepository with several paths. When path does not exist, an Exception was thrown. Empty path will not be added. When you do not have one of the default directories, you can set it with an empty value to not throw an exception.

Object creation

ParsedClassRepository repository = new ParsedClassRepository(
        Paths.get("src/test/java")
);
ParsedClassRepository repository = new ParsedClassRepository(
        Paths.get("src/main/java"),
        Paths.get("src/test/java")
);
ParsedClassRepository repository = new ParsedClassRepository(
        Paths.get(""),
        Paths.get("src/test/java")
);

Exception

java.lang.IllegalArgumentException: Only directories are allowed as root path: src/UNKNOWN/java
ParsedClassRepository repository = new ParsedClassRepository(
        Paths.get("src/UNKNOWN/java")
);

Parsed classes only once

The ParsedClassRepository have a cache to avoid parsing twice the same class.

Below, we show calls to parse method when we call a method of ParsedClassRepository. clearCache method clears the cache and classes need to parse again.

  • clearCache()

  • getComment(ApprovalsExtensionTest.class)

    • parse(com.github.docastest.doctesting.junitextension, ApprovalsExtensionTest.java.class)

  • getComment(DocPathTest.class)

    • parse(com.github.docastest.doctesting.utils, DocPathTest.java.class)

  • getComment(ApprovalsExtensionTest.class)

  • getComment(ApprovalsExtensionTest.class, using_extension)

  • getComment(FailureReporterTest.class)

    • parse(com.github.docastest.doctesting.junitextension, FailureReporterTest.java.class)

  • clearCache()

  • getComment(ApprovalsExtensionTest.class)

    • parse(com.github.docastest.doctesting.junitextension, ApprovalsExtensionTest.java.class)