How to properly handle a conditional deprecation?
已回答
In my Missing In Actions plugin, I have to get code style settings to retrieve indent tab size from CodeStyleSettings. In the case that a PsiFile is null, the fallback is to use CodeStyleSettingsManager.getInstance().getSettings(project). This is flagged as deprecated usage, but the comment on the method states that it should only be used as a last resort when PsiFile is not available. Here is the code, with the comment copied from IC-2021.2.4 sources:
VirtualFile virtualFile = editor.getVirtualFile();
PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile);
Language language = psiFile == null ? null : psiFile.getLanguage();
/* From the deprecation comment:
Use one of the following methods:
CodeStyle.getLanguageSettings(PsiFile, Language) to get common settings for a language.
CodeStyle.getCustomSettings(PsiFile, Class) to get custom settings.
If PsiFile is not applicable, use CodeStyle.getSettings(Project) but only in cases when using main project settings
is logically the only choice in a given context. It shouldn't be used just because the existing code doesn't allow
to easily retrieve a PsiFile. Otherwise, the code will not catch up with proper file code style settings since the
settings may differ for different files depending on their scope.
vsch: in this case it is definitely the only choice, since the psiFile is not available when this call is made
*/
@SuppressWarnings("deprecation")
CommonCodeStyleSettings styleSettings = psiFile != null ? CodeStyle.getLanguageSettings(psiFile, language) : CodeStyleSettingsManager.getSettings(project);
IndentOptions indentOptions = styleSettings.getIndentOptions();
I understand that the deprecation was put there to emphasize that you need a psiFile to accurately get code style settings, which can be per file. In my case, my usage of the method is correct.
Am I to just ignore this conditional deprecation and live with the plugin verifier complaints, as I have been doing up to now?
请先登录再写评论。
Hi Vladimir,
The Javadoc points to
CodeStyle.getSettings(Project)(not deprecatedCodeStyleSettingsManager.getSettings(Project), which is a static method that works the same way (implementation detail) but is not deprecated.Hi Karol,
Thank you for pointing out the static alternative. It is what I need.