Find usage of ID in string literal
Hello,
I'm trying to add support for OSGi Declarative Services annotations to my plugin and I'm struggling with a problem with "Find Usages". Java classes are annotated with a @Component annotation to indicate that the class represents an OSGi component. By default, the qualified name of that class is used to identify the component, e.g. for configuration purposes. However, it's also possible to set a custom name via the annotation's "name" attribute, e.g.:
@Component(name = "MyCustomName")
public class MyComponent {
...
}
Finding usages on the class itself, works perfectly, but it's not possible to find usages on a Java string literal. I tried to replace the default JavaFindUsagesProvider to allow string literals, but it's not picked up.
My current solution is very complex and involves a custom language that consists only of a single PSI element. I inject that custom language into the string literal and provide a FindUsagesProvider for it.
It works but I'd prefer to have a simpler solution. Is there a simpler way to achieve the same?
Ciao, Victor.
Please sign in to leave a comment.
Hi Victor,
I'd suggest to register additional reference searcher which would detect annotation attribute and start search for corresponding string literal.
The sample of a custom reference searcher. It uses the index of all places where corresponding reference on the component may appear and then enumerate all such references checking if it resolves to the component. Looks like that similar approach should work in your case as well
Anna
Hi Anna,
thanks a lot for your feedback. I already implemented a reference searcher, but the problem is that it's never called. When I select "Find Usages" on the string literal it shows the following message:
Is there a way to achieve this? To make it hopefully clear what I wanna achieve: I want usages of the ID that is the string literal inside a PsiLiteralExpression.
Ciao, Victor.
Ah, that's the opposite direction. You need to add reference to the string literal through `com.intellij.psi.PsiReferenceContributor` which will resolve to the class
Hi Anna,
sorry, I think the screenshot is a bit confusing. The string inside the annotation attribute is not a reference to the class. It can be an arbitrary string, e.g. "foobar". So there should be other elements that have references to the string literal.
I think the reference search that you mentioned in your first reply is the right approach. The only problem is that it's never called.
Ciao, Victor.
I suggest to make reference from the string. Is that correct that other elements may reference the class by fully qualified name or by this string literal? If so, then it's feasible to pretend that string literal references the class as well.
Anna