JDK availability check
已回答
Hi
What is the recommended way of finding whether a specific JDK class, e.g. Optional<T>, is available?
One option I explored was to find the project SDK, and compare that to the JDK version I need, e.g. in the case of Optional<T> that is 1.8. However, this is not a robust solution since the user might have renamed the SDK or, as in the case of plugin developers, use an SDK that in itself contains JDK which would then fail the previous check.
Another option I thought of was to use
PsiClassType optionalType = PsiElementFactory.createTypeByFQClassName(CommonClassNames.JAVA_UTIL_OPTIONAL);
return optionalType.resolve() != null;
Which I found to be more reliable than the previous option.
Radu
请先登录再写评论。
You can check JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_UTIL_OPTIONAL, scope) != null instead. 'scope' arguments describes where the class will be searched. If you invoke this code from some inspection or a quick fix and have an PsiElement where java.util.Optional is supposed to be used, you can call psiElement.getResolveScope(), it'll return scope containing all modules, libraries and SDK from the dependencies of the module containing that psiElement.