Structural search and generic types

Answered

I'm trying to find instances of Map.get() where the argument is a string instead of the expected object type. Trivial example code:

import java.util.HashMap;
import java.util.Map;

public class Main {
public static void main(String[] args) {
Map<Example, String> testMap = new HashMap<>();
testMap.put(new Example(), "something");
String value = testMap.get("a string");
}
}

class Example {}

The testMap.get() call is what I want to match.

I try a structured search for a simple expression, just "$expr$" (minus the double quotes). In the variables dialog I set the expression type to String and the expected type to Example. I would have expected it to find the parameter of the get() call but it comes up empty.

However, if I change it to this:

public class Main {
public static void main(String[] args) {
doSomething("foo");
}

private static void doSomething(Example obj) {}
}

class Example {}

The search succeeds and finds "foo". So clearly it's able to match method arguments.

Does the "expected type" feature of structural search not pay attention to generics? Or am I fundamentally misunderstanding something?

2 comments
Comment actions Permalink
Official comment

Unfortunately because the expected type of the argument of the get() method is Object, and not a generic parameter, you can't use a query like that to find it. I don't know of a way to find what you want using Structural Search. However you may want to try the inspection "Suspicious collections method calls", which warns on method calls like your example.

 

Bas

Comment actions Permalink

Thanks, I was afraid of that. Unfortunately what I actually want in this case is structural replace, which the inspection won't do for me. Time to do it by hand.

0

Please sign in to leave a comment.