Kind.IDENTIFIER package name

i am trying to develop a custom rule: unit test’s entrypoint should be in a specific package.
i have a following test:

    CBCCrmContactServiceDelegateImpl cbcCrmContactServiceDelegate;

    public void createContactSuccess() {
        ContactInfo createContactReq = buildCreatContactReq();


        cbcCrmContactServiceDelegate.createContact(null, createContactReq);

i need to find out cbcCrmContactServiceDelegate 's package name , i am using visitMethodInvocation and i can find the IdentifierTreeImpl by using methodSelect and expression, but can’t find a way to find the identifier’s package name

Hello @dassio

At this point, you should probably have a look at the semantic API.

From an identifier, you can get a symbol. If you loop over the owner until finding a package symbol, you could find what you need.

  private static String packageNameOf(Symbol symbol) {
    Symbol owner = symbol.owner();
    while (!owner.isPackageSymbol()) {
      owner = owner.owner();

Alternatively, you can also rely on types: tree.symbol().type().

I let you play with the semantic API, you will probably find what you need.
Hope it helps,

thanks for the help

the package found using this way is the test class’s package name, not the implementation’s package name

I finally used JavaFileScannerContext context.getTree().imports() to find all the imports and manually match the package by using expression.symbolType()

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.