下面列出了怎么用com.intellij.psi.JavaPsiFacade的API类实例代码及写法,或者点击链接到github查看源代码。
@VisibleForTesting
static PsiExpression createMethodChain(
Project project, String firstName, List<? extends String> methodNames) {
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
StringBuilder expressionText =
new StringBuilder(firstName + "(" + TEMPLATE_INSERT_PLACEHOLDER_C + ")");
methodNames.forEach(
methodName ->
expressionText
.append("\n.")
.append(methodName)
.append("(")
.append(TEMPLATE_INSERT_PLACEHOLDER)
.append(")"));
return factory.createExpressionFromText(expressionText.toString(), null);
}
/**
* Adds comment to the given method "// An event handler ContextClassName.methodName(c,
* parameterName)
*/
public static void addComment(PsiClass contextClass, PsiMethod method) {
final Project project = contextClass.getProject();
final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
final StringBuilder builder =
new StringBuilder("// An event handler ")
.append(LithoPluginUtils.getLithoComponentNameFromSpec(contextClass.getName()))
.append(".")
.append(method.getName())
.append("(")
.append(CONTEXT_PARAMETER_NAME);
for (PsiParameter parameter : method.getParameterList().getParameters()) {
if (LithoPluginUtils.isParam(parameter)) {
builder.append(", ").append(parameter.getName());
}
}
builder.append(")");
final PsiComment comment = factory.createCommentFromText(builder.toString(), method);
method.addBefore(comment, method.getModifierList());
}
/**
* @param qualifiedName the name of the class to create lookup
* @param project to find the lookup annotation class
* @param insertHandler adds custom actions to the insert handling
* @throws IncorrectOperationException if the qualifiedName does not specify a valid type
* @return new {@link LookupElement} or cached instance if it was created previously
*/
static LookupElement create(
String qualifiedName, Project project, InsertHandler<LookupElement> insertHandler)
throws IncorrectOperationException {
if (CACHE.containsKey(qualifiedName)) {
return CACHE.get(qualifiedName);
}
PsiClass typeCls = PsiSearchUtils.findClass(project, qualifiedName);
if (typeCls != null) {
SpecLookupElement lookupElement = new SpecLookupElement(typeCls, insertHandler);
CACHE.put(qualifiedName, lookupElement);
return lookupElement;
}
// This is a dummy class, we don't want to cache it.
typeCls =
JavaPsiFacade.getInstance(project)
.getElementFactory()
.createClass(LithoClassNames.shortName(qualifiedName));
return new SpecLookupElement(typeCls, insertHandler);
}
@Test
public void createAddMethodCallFix() {
testHelper.getPsiClass(
classes -> {
// Setup test environment
PsiClass cls = classes.get(0);
PsiMethodCallExpression call =
PsiTreeUtil.findChildOfType(cls, PsiMethodCallExpression.class);
Project project = testHelper.getFixture().getProject();
PsiElementFactory factory = JavaPsiFacade.getInstance(project).getElementFactory();
Editor editor = mock(Editor.class);
when(editor.getCaretModel()).thenReturn(mock(CaretModel.class));
IntentionAction fix =
AddArgumentFix.createAddMethodCallFix(call, "ClassName", "methodName", factory);
assertThat(call.getArgumentList().getExpressions()[0].getText())
.isNotEqualTo("ClassName.methodName()");
fix.invoke(project, editor, testHelper.getFixture().getFile());
assertThat(call.getArgumentList().getExpressions()[0].getText())
.isEqualTo("ClassName.methodName()");
return true;
},
"RequiredPropAnnotatorTest.java");
}
@Nullable
public static PsiType safeGetValidType(@NotNull Module module, @NotNull String fqn) {
try {
// Intellij expects inner classes to be referred via `.` instead of `$`
PsiType type = JavaPsiFacade.getInstance(module.getProject()).getParserFacade()
.createTypeFromText(fqn.replaceAll("\\$", "."), null);
boolean typeValid = isValidType(type);
if (typeValid) {
if (type instanceof PsiClassType) {
return PsiClassType.class.cast(type);
} else if (type instanceof PsiArrayType) {
return PsiArrayType.class.cast(type);
}
}
return null;
} catch (IncorrectOperationException e) {
debug(() -> log.debug("Unable to find class fqn " + fqn));
return null;
}
}
/** Ui for the user to pick the Main class. */
@NotNull
public TreeClassChooser chooseMainClassForProject() {
logger.info("Choosing main class for project.");
TreeClassChooser chooser;
Project project = new ObjectFinder().findCurrentProject();
while (true) {
TreeClassChooserFactory factory = TreeClassChooserFactory.getInstance(project);
GlobalSearchScope scope;
scope = GlobalSearchScope.moduleScope(module);
PsiClass ecClass = JavaPsiFacade.getInstance(project).findClass("", scope);
ClassFilter filter = createClassFilter();
chooser =
factory.createInheritanceClassChooser(
"Choose main class", scope, ecClass, null, filter);
chooser.showDialog();
if (chooser.getSelected() == null
|| chooser.getSelected().findMethodsByName("main", true).length > 0) {
logger.info("Choosing main class aborted.");
break;
}
}
logger.info("Main class chosen successfully.");
return chooser;
}
private File getSourceFileForClass(String className) {
return ApplicationManager.getApplication()
.runReadAction(
(Computable<File>)
() -> {
try {
PsiClass psiClass =
JavaPsiFacade.getInstance(project)
.findClass(className, GlobalSearchScope.projectScope(project));
if (psiClass == null) {
return null;
}
return VfsUtilCore.virtualToIoFile(
psiClass.getContainingFile().getVirtualFile());
} catch (IndexNotReadyException ignored) {
// We're in dumb mode. Abort! Abort!
return null;
}
});
}
public void testModuleRunConfiguration() throws Throwable {
doImport("testprojects/tests/java/org/pantsbuild/testproject/testjvms");
PsiPackage testPackage = JavaPsiFacade.getInstance(myProject).findPackage("org.pantsbuild.testproject.testjvms");
assertEquals(1, testPackage.getDirectories().length);
ExternalSystemRunConfiguration esc = getExternalSystemRunConfiguration(testPackage.getDirectories()[0]);
Set<String> expectedItems = ProjectTestJvms.testClasses(myProject, getProjectPath())
.map(aClass -> "--test-junit-test=" + aClass.getQualifiedName())
.collect(Collectors.toSet());
assertNotEmpty(expectedItems);
Set<String> items = new HashSet<>(Arrays.asList(esc.getSettings().getScriptParameters().split(" ")));
assertContains(items, expectedItems);
}
@Override
public void onGenerateFinished(boolean result, File file) {
SaveAndSyncHandlerImpl.refreshOpenFiles();
VirtualFileManager.getInstance().refreshWithoutFileWatcher(false);
ProjectManagerEx.getInstanceEx().unblockReloadingProjectOnExternalChanges();
project.getBaseDir().refresh(false, true);
if (null == JavaPsiFacade.getInstance(project).findPackage("com.magnet.android.mms.async")) {
showMissingDependencies();
}
if (!result) {
showCloseDialog(file);
} else {
getThis().setVisible(true);
}
}
public static Set<String> getQualifierAnnotations(PsiElement element) {
Set<String> qualifiedClasses = new HashSet<String>();
if (element instanceof PsiModifierListOwner) {
PsiModifierListOwner listOwner = (PsiModifierListOwner) element;
PsiModifierList modifierList = listOwner.getModifierList();
if (modifierList != null) {
for (PsiAnnotation psiAnnotation : modifierList.getAnnotations()) {
if (psiAnnotation != null && psiAnnotation.getQualifiedName() != null) {
JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(element.getProject());
PsiClass psiClass = psiFacade.findClass(psiAnnotation.getQualifiedName(),
GlobalSearchScope.projectScope(element.getProject()));
if (hasAnnotation(psiClass, CLASS_QUALIFIER)) {
qualifiedClasses.add(psiAnnotation.getQualifiedName());
}
}
}
}
}
return qualifiedClasses;
}
private boolean navigateToConstructorIfProvider(PsiParameter psiParameter) {
PsiTypeElement declaringTypeElement = psiParameter.getTypeElement();
PsiClass classElement = JavaPsiFacade.getInstance(psiParameter.getProject()).findClass(
declaringTypeElement.getType().getCanonicalText(),
declaringTypeElement.getResolveScope());
if (classElement == null) {
return false;
}
for (PsiMethod method : classElement.getConstructors()) {
if (PsiConsultantImpl.hasAnnotation(method, CLASS_INJECT) && navigateToElement(method)) {
return true;
}
}
return false;
}
private static Set<PsiClass> findPsiClasses(Project project, String className) {
GlobalSearchScope scope = GlobalSearchScope.everythingScope(project);
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
PsiShortNamesCache psiShortNamesCache = PsiShortNamesCache.getInstance(project);
Set<PsiClass> results = new HashSet<>();
BuckAutoDepsSearchableClassNameContributor.EP_NAME.getExtensions(project).stream()
.filter(contributor -> contributor.isApplicable(project, className))
.forEach(
contributor ->
contributor
.getSearchableClassNames(project, className)
.forEach(
name ->
Stream.concat(
Stream.of(javaPsiFacade.findClasses(name, scope)),
Stream.of(psiShortNamesCache.getClassesByName(name, scope)))
.distinct()
.forEach(
psiClass -> {
if (!results.contains(psiClass)
&& contributor.filter(project, className, psiClass)) {
results.add(psiClass);
}
})));
return results;
}
public JNIFunction2JavaMethodBinding(String jniFunctionName, PsiManager psiManager) {
int lastUnderscoreIndex = jniFunctionName.lastIndexOf('_');
String className = jniFunctionName.substring(0, lastUnderscoreIndex).replace('_','.').substring(JAVA_NATIVE_PREFIX.length());
String methodName = jniFunctionName.substring(lastUnderscoreIndex + 1);
Project project = psiManager.getProject();
clazz = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.projectScope(project));
PsiMethod m = null;
if (clazz != null) {
PsiMethod[] psiMethods = clazz.findMethodsByName(methodName, false);
if (psiMethods.length > 0) {
m = psiMethods[0];
}
}
method = m;
}
public DocCommentProcessor(PsiFile file) {
this.file = file;
if ( file == null ) {
project = null;
markdownOptions = null;
psiElementFactory = null;
}
else {
project = file.getProject();
psiElementFactory = JavaPsiFacade.getInstance(project).getElementFactory();
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
Module module = fileIndex.getModuleForFile(file.getVirtualFile());
if ( module == null ) {
markdownOptions = null;
}
else if ( !fileIndex.isInSourceContent(file.getVirtualFile()) ) {
markdownOptions = null;
}
else if ( !Plugin.moduleConfiguration(module).isMarkdownEnabled() ) {
markdownOptions = null;
}
else {
markdownOptions = Plugin.moduleConfiguration(module).getRenderingOptions();
}
}
}
private void scheduleRefreshOfEventFiles() {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
Set<String> eventClasses;
synchronized (allEventClasses) {
eventClasses = new HashSet<String>(allEventClasses);
}
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(myProject);
DaemonCodeAnalyzer codeAnalyzer = DaemonCodeAnalyzer.getInstance(myProject);
for (String eventClass : eventClasses) {
PsiClass eventPsiClass = javaPsiFacade.findClass(eventClass,
GlobalSearchScope.allScope(myProject));
if (eventPsiClass == null) continue;
PsiFile psiFile = eventPsiClass.getContainingFile();
if (psiFile == null) continue;
codeAnalyzer.restart(psiFile);
}
}
});
}
public static <T> T getAttributeValue(final PsiAnnotation configAnnotation, String attribute) {
final PsiAnnotationMemberValue attributeValue = configAnnotation.findAttributeValue(attribute);
if (attributeValue == null) {
return null;
}
final PsiConstantEvaluationHelper evaluationHelper = JavaPsiFacade.getInstance(attributeValue.getProject())
.getConstantEvaluationHelper();
return (T) evaluationHelper.computeConstantExpression(attributeValue);
}
public GodClassUserInputDialog(AbstractExtractClassRefactoring abstractRefactoring, AbstractRefactoringPanel godClassPanel) {
super(abstractRefactoring.getRefactoring().getSourceFile().getProject(), true);
this.abstractRefactoring = abstractRefactoring;
this.refactoring = abstractRefactoring.getRefactoring();
String packageName = PsiUtil.getPackageName(refactoring.getSourceClass());
parentPackage = JavaPsiFacade.getInstance(refactoring.getProject()).findPackage(packageName);
this.godClassPanel = godClassPanel;
initialiseControls();
setTitle(IntelliJDeodorantBundle.message("god.class.dialog.title"));
init();
}
/**
* Create a search pattern for the given <code>className</code> class name.
*
* @param annotationName the class name to search.
* @return a search pattern for the given <code>className</code> class name.
*/
protected static Query<PsiModifierListOwner> createAnnotationTypeDeclarationSearchPattern(SearchContext context, String annotationName) {
JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(context.getModule().getProject());
PsiClass annotationClass = javaPsiFacade.findClass(annotationName, GlobalSearchScope.allScope(context.getModule().getProject()));
if (annotationClass != null) {
return new ArrayQuery<>(annotationClass);
} else {
return new EmptyQuery<>();
}
}
@Override
protected void processAnnotation(PsiModifierListOwner psiElement, PsiAnnotation configPropertyAnnotation,
String annotationName, SearchContext context) {
if (psiElement instanceof PsiField || psiElement instanceof PsiMethod || psiElement instanceof PsiParameter) {
IPropertiesCollector collector = context.getCollector();
String name = AnnotationUtils.getAnnotationMemberValue(configPropertyAnnotation,
QuarkusConstants.CONFIG_PROPERTY_ANNOTATION_NAME);
if (StringUtils.isNotEmpty(name)) {
String propertyTypeName = "";
if (psiElement instanceof PsiField) {
propertyTypeName = PsiTypeUtils.getResolvedTypeName((PsiField) psiElement);
} else if (psiElement instanceof PsiMethod) {
propertyTypeName = PsiTypeUtils.getResolvedResultTypeName((PsiMethod) psiElement);
} else if (psiElement instanceof PsiVariable) {
propertyTypeName = PsiTypeUtils.getResolvedTypeName((PsiVariable) psiElement);
}
PsiClass fieldClass = JavaPsiFacade.getInstance(psiElement.getProject()).findClass(propertyTypeName, GlobalSearchScope.allScope(psiElement.getProject()));
String type = PsiTypeUtils.getPropertyType(fieldClass, propertyTypeName);
String description = null;
String sourceType = PsiTypeUtils.getSourceType(psiElement);
String sourceField = null;
String sourceMethod = null;
if (psiElement instanceof PsiField || psiElement instanceof PsiMethod) {
sourceField = PsiTypeUtils.getSourceField((PsiMember) psiElement);
} else if (psiElement instanceof PsiParameter) {
PsiMethod method = (PsiMethod) ((PsiParameter)psiElement).getDeclarationScope();
sourceMethod = PsiTypeUtils.getSourceMethod(method);
}
String defaultValue = AnnotationUtils.getAnnotationMemberValue(configPropertyAnnotation,
QuarkusConstants.CONFIG_PROPERTY_ANNOTATION_DEFAULT_VALUE);
String extensionName = null;
super.updateHint(collector, fieldClass);
addItemMetadata(collector, name, type, description, sourceType, sourceField, sourceMethod, defaultValue,
extensionName, PsiTypeUtils.isBinary(psiElement));
}
}
}
static PsiClass getOrCreateClass(String qualifiedClassName, Project project) {
PsiClass cls = PsiSearchUtils.findClass(project, qualifiedClassName);
if (cls == null) {
cls =
JavaPsiFacade.getElementFactory(project)
.createClass(LithoClassNames.shortName(qualifiedClassName));
}
return cls;
}
private PsiMethod readMethodTemplate(String targetName, Project project) {
// TemplateSettings#loadDefaultLiveTemplates
PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
return Optional.ofNullable(
DecodeDefaultsUtil.getDefaultsInputStream(this, "methodTemplates/methods"))
.map(TemplateService::load)
.filter(element -> TAG_ROOT.equals(element.getName()))
.map(element -> element.getChild(targetName))
.map(template -> template.getAttributeValue("method"))
.map(method -> factory.createMethodFromText(method, null))
.orElse(null);
}
@Override
public void invoke(Project project, Editor editor, PsiFile file)
throws IncorrectOperationException {
final AtomicReference<PsiMethod> eventMethodRef = new AtomicReference<>();
final Runnable generateOnEvent =
() ->
OnEventGenerateAction.createHandler(
(context, eventProject) -> event, eventMethodRef::set)
.invoke(project, editor, file);
final Runnable updateArgumentList =
() ->
Optional.ofNullable(eventMethodRef.get())
.map(
eventMethod ->
AddArgumentFix.createArgumentList(
methodCall,
clsName,
eventMethod.getName(),
JavaPsiFacade.getInstance(project).getElementFactory()))
.ifPresent(argumentList -> methodCall.getArgumentList().replace(argumentList));
final Runnable action =
() -> {
TransactionGuard.getInstance().submitTransactionAndWait(generateOnEvent);
WriteCommandAction.runWriteCommandAction(project, updateArgumentList);
ComponentGenerateUtils.updateLayoutComponent(layoutCls);
LithoLoggerProvider.getEventLogger().log(EventLogger.EVENT_FIX_EVENT_HANDLER + ".new");
};
final Application application = ApplicationManager.getApplication();
if (application.isUnitTestMode()) {
action.run();
} else {
application.invokeLater(action);
}
}
@Test
public void createHandler_generateOnEvent() {
testHelper.getPsiClass(
classes -> {
final CodeInsightTestFixture fixture = testHelper.getFixture();
final PsiFile psiFile = classes.get(0).getContainingFile();
final LightVirtualFile virtualFile =
new LightVirtualFile(psiFile.getName(), psiFile.getFileType(), psiFile.getText());
final String generatedOnEvent =
"@com.facebook.litho.annotations.OnEvent(TestClass.class)\n"
+ " static void onTestClass(com.facebook.litho.ComponentContext c) {\n"
+ " }";
final PsiClass eventClass =
JavaPsiFacade.getInstance(fixture.getProject())
.getElementFactory()
.createClass("TestClass");
fixture.openFileInEditor(virtualFile);
assertThat(fixture.getEditor().getDocument().getText()).doesNotContain(generatedOnEvent);
TransactionGuard.getInstance()
.submitTransactionAndWait(
() ->
OnEventGenerateAction.createHandler(
(context, project) -> eventClass,
onEvent -> {
assertThat(onEvent.getName()).isEqualTo("onTestClass");
assertThat(onEvent.getAnnotations()[0].getQualifiedName())
.isEqualTo("com.facebook.litho.annotations.OnEvent");
})
.invoke(fixture.getProject(), fixture.getEditor(), fixture.getFile()));
assertThat(fixture.getEditor().getDocument().getText()).contains(generatedOnEvent);
return true;
},
"LayoutSpec.java");
}
@Test
public void invoke() {
testHelper.getPsiClass(
classes -> {
final CodeInsightTestFixture fixture = testHelper.getFixture();
final PsiMethodCallExpression call =
PsiTreeUtil.findChildOfType(classes.get(0), PsiMethodCallExpression.class);
final LightVirtualFile virtualFile = createVirtualFile(classes.get(0));
final String generatedOnEvent =
"@com.facebook.litho.annotations.OnEvent(TestClass.class)\n"
+ " static void onTestClass(com.facebook.litho.ComponentContext c) {\n"
+ " }";
final PsiClass eventClass =
JavaPsiFacade.getInstance(fixture.getProject())
.getElementFactory()
.createClass("TestClass");
fixture.openFileInEditor(virtualFile);
assertThat(fixture.getEditor().getDocument().getText()).doesNotContain(generatedOnEvent);
AddArgumentFix.createNewMethodCallFix(
call, "TestName", eventClass, Mockito.mock(PsiClass.class))
.invoke(fixture.getProject(), fixture.getEditor(), fixture.getFile());
assertThat(fixture.getEditor().getDocument().getText()).contains(generatedOnEvent);
assertThat(call.getArgumentList().getExpressions()[0].getText())
.isEqualTo("TestName.onTestClass()");
return true;
},
"EventHandlerAnnotatorSpec.java");
}
/**
* Check whether classpath of a module that corresponds to a {@link PsiElement} contains given class.
*
* @param project Project
* @param psiElement Element for which we check the class
* @param className Class name of the searched class
* @return True if the class is present on the classpath
* @since 1.3
*/
public static boolean isClassAvailableForPsiFile(@NotNull Project project, @NotNull PsiElement psiElement, @NotNull String className) {
Module module = ModuleUtil.findModuleForPsiElement(psiElement);
if (module == null) {
return false;
}
GlobalSearchScope moduleScope = module.getModuleWithDependenciesAndLibrariesScope(false);
PsiClass classInModule = JavaPsiFacade.getInstance(project).findClass(className, moduleScope);
return classInModule != null;
}
@Override public VirtualFile findFileByFQName(String file, Project project) {
VirtualFile result = null;
if (file != null) {
PsiClass aClass = JavaPsiFacade.getInstance(project).findClass(file, GlobalSearchScope.allScope(project));
if (aClass != null && aClass.getNavigationElement().getContainingFile().getName().endsWith(".java")) {
result = aClass.getNavigationElement().getContainingFile().getVirtualFile();
}
}
return result;
}
@Override
public void computeSourcePosition(@NotNull XNavigatable navigatable) {
PsiClass aClass = JavaPsiFacade.getInstance(session.getProject()).findClass(messageProcessorInfo.getClassName(), GlobalSearchScope.allScope(session.getProject()));
if (aClass != null) {
navigatable.setSourcePosition(MuleConfigUtils.createPositionByElement(aClass));
}
}
@Override
public void computeSourcePosition(@NotNull XNavigatable navigatable) {
PsiClass aClass = JavaPsiFacade.getInstance(session.getProject()).findClass(fieldDefinition.getClassName(), GlobalSearchScope.allScope(session.getProject()));
if (aClass != null) {
navigatable.setSourcePosition(MuleConfigUtils.createPositionByElement(aClass));
}
}
public List<ReferenceableBeanId> findReferenceableBeanIdsByType(Module module,
Predicate<String> idCondition,
PsiType expectedBeanType) {
PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(module.getProject());
return findReferenceableBeanIds(module, idCondition).stream()
.filter(ref -> {
PsiClass psiClass = resolveToPsiClass(ref);
if (psiClass != null) {
PsiClassType beanType = elementFactory.createType(psiClass);
return expectedBeanType.isAssignableFrom(beanType);
}
return false;
})
.collect(Collectors.toList());
}
/**
* Return a list of {@link PsiClass}s annotated with the specified annotation
* @param project - Project reference to narrow the search inside.
* @param annotation - the full qualify annotation name to search for
* @return a list of classes annotated with the specified annotation.
*/
@NotNull
private Collection<PsiClass> getClassesAnnotatedWith(Project project, String annotation) {
PsiClass stepClass = JavaPsiFacade.getInstance(project).findClass(annotation, ProjectScope.getLibrariesScope(project));
if (stepClass != null) {
final Query<PsiClass> psiMethods = AnnotatedElementsSearch.searchPsiClasses(stepClass, GlobalSearchScope.allScope(project));
return psiMethods.findAll();
}
return Collections.emptyList();
}