Is it possible to add inspection settings for "forbidden" methods?

For example I want to add String.getBytes() (no args) as a "forbidden" method so it gives an error (or at least a warning), is this possible in Idea 13 (and/or 14)?

2 comments
Comment actions Permalink

You can do this using the "Structural Search Inspection".

  1. Go into Settings > Inspections > General > Structural Search Inspection and turn it on.
  2. Click the Add button add2.png and select to add a Search Template
  3. Click the Copy existing template button (on lower right)
  4. From the list, Select expressions > method calls and click OK
  5. Click the Edit Variables button
  6. With Instance selected on the left, in the middle "Expression constraints" section, enter "String" (w/o the quotes) for the "Text/regexp for java expression type"
  7. With MethodCall selected on the left, in the top "Text Constraints" section, enter "getBytes" (w/o the quotes) for the"Text/regexp" field at the top
  8. With Parameter selected on the left, in the "Occurrence count" section, set both the minimum and maximum count to 0 (you'll need to uncheck "unlimited")
  9. Click OK to close the Edit Variables dialog
  10. Click OK to close the Structural Search dialog
  11. Provide a name for the template.
    • The name of the template is what will appear in the inspection waring popup. So you likely want to make it something meaningful like "Call to String.getBytes() without a Charset Parameter"
  12. Set the severity warning you want for the inspection in the inspection dialog and click OK


Now any call's on the no parameters version of getBytes() on a variable of type String will be highlighted (as defined by the sevierity level you selected for the inspection).

If you also want a quick fix modify the code (i.e. to automatically add the call to a Charset), you can do that as well. Follow the above instructions with the following modifications:

  • For step 2, select "Replace Template" rather than search template
  • For step 6, (when editing the Instance criteria) in addition to what is listed above, uncheck the "This variable is target of the search" at the bottom
  • For step 8, (when editing the Parameter criteria) in addition to what is listed above, check the "This variable is target of the search" at the bottom
  • As Step 9B, in the "Replacement Template" section, enter something like the following (this use the UTF_8 constant from the Guava library. Use whatever you use).
    • $Instance$.$MethodCall$(com.google.common.base.Charsets.UTF_8)
    • Set the options at the bottom, such as "shorten fully qualified names) as desired

Now when you get the warning, you will have a quick fix option available via Alt+Enter to change it to a call with a Charset defined.

    0
    Comment actions Permalink

    Thanks it worked like a charm!
    I have never use the Structural Search before but it is very powerfull :)

    0

    Please sign in to leave a comment.