How to check try-with-resources for a static method call in custom plugin?

  • What language are you writing rules for? Java

  • What have you tried, and what’s your challenge / stumbling block

  @Override
	  public List<Tree.Kind> nodesToVisit() {
		  return Arrays.asList(Tree.Kind.MEMBER_SELECT);
	  }

	  @Override
	  public void visitNode(Tree tree) {
		  MemberSelectExpressionTree mse = (MemberSelectExpressionTree) tree;
		    String name = mse.identifier().name();
		    if(mse.is(Kind.MEMBER_SELECT) && name.equals("mockStatic")) {
		    	System.out.println("name "+name);
		    }

	  
	  }

How can I check if this member has a try-with-resources before when I use method mockStatic()?

This what I want to make sure the code looks like:

try (MockedStatic<StaticUtils> utilities = Mockito.mockStatic(StaticUtils.class)) {
        <More code here>
    }

or this is also valid

try (MockedStatic<StaticUtils> utilities = mockStatic(StaticUtils.class)) {
        <More code here>
    }

br,

//mike

Hi Mikael,

I’d suggest to use visitTryStatement and going down it’s resourcesList instead of looking for a MemberSelectExpressionTree and going up it’s parents. That’s nearer at your use case and more performant (you will usually have less try-statements in the analyzed code than member expressions).

    @Override
    public void visitTryStatement(TryStatementTree tree) {
        scan(tree.resourceList());
        // or do something else with tree.resourceList()
    }

Best regards,

Marco

1 Like