com.intellij.psi.PsiMethod Java Examples
The following examples show how to use
com.intellij.psi.PsiMethod.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DebugLintIssue.java From Debug with Apache License 2.0 | 6 votes |
@Nullable @Override public UElementHandler createUastHandler(@NotNull final JavaContext context) { return new UElementHandler() { @Override public void visitCallExpression(@NotNull UCallExpression node) { final PsiMethod psiMethod = node.resolve(); if (psiMethod != null && context.getEvaluator().isMemberInClass(psiMethod, "io.noties.debug.Debug")) { final String name = node.getMethodName(); if (name != null && METHODS.contains(name)) { process(context, node); } } } }; }
Example #2
Source File: UppercaseStatePropInspection.java From litho with Apache License 2.0 | 6 votes |
@Nullable @Override public ProblemDescriptor[] checkMethod( @NotNull PsiMethod method, @NotNull InspectionManager manager, boolean isOnTheFly) { if (!LithoPluginUtils.isLithoSpec(method.getContainingClass())) { return ProblemDescriptor.EMPTY_ARRAY; } return Optional.of(method) .map(PsiMethod::getParameterList) .map(PsiParameterList::getParameters) .map( psiParameters -> Stream.of(psiParameters) .filter(LithoPluginUtils::isPropOrState) .filter(UppercaseStatePropInspection::isFirstLetterCapital) .map(PsiParameter::getNameIdentifier) .filter(Objects::nonNull) .map(identifier -> createWarning(identifier, manager, isOnTheFly)) .toArray(ProblemDescriptor[]::new)) .orElse(ProblemDescriptor.EMPTY_ARRAY); }
Example #3
Source File: ReturnVariableGenerator.java From easy_javadoc with Apache License 2.0 | 6 votes |
@Override public String generate(PsiElement element) { if (!(element instanceof PsiMethod)) { return ""; } PsiMethod psiMethod = (PsiMethod) element; String returnName = psiMethod.getReturnType() == null ? "" : psiMethod.getReturnType().getPresentableText(); if (Consts.BASE_TYPE_SET.contains(returnName)) { return returnName; } else if ("void".equalsIgnoreCase(returnName)) { return ""; } else { return String.format("{@link %s }", returnName); } }
Example #4
Source File: AnnotatorUtils.java From litho with Apache License 2.0 | 6 votes |
static void addError( AnnotationHolder holder, SpecModelValidationError error, List<IntentionAction> fixes) { PsiElement errorElement = (PsiElement) error.element; Annotation errorAnnotation = holder.createErrorAnnotation( Optional.of(errorElement) .filter(element -> element instanceof PsiClass || element instanceof PsiMethod) .map(PsiNameIdentifierOwner.class::cast) .map(PsiNameIdentifierOwner::getNameIdentifier) .orElse(errorElement), error.message); if (!fixes.isEmpty()) { for (IntentionAction fix : fixes) { errorAnnotation.registerFix(fix); } } }
Example #5
Source File: ProducerUtils.java From intellij with Apache License 2.0 | 6 votes |
@Nullable public static Location<PsiMethod> getMethodLocation(Location<?> contextLocation) { Location<PsiMethod> methodLocation = getTestMethod(contextLocation); if (methodLocation == null) { return null; } if (contextLocation instanceof PsiMemberParameterizedLocation) { PsiClass containingClass = ((PsiMemberParameterizedLocation) contextLocation).getContainingClass(); if (containingClass != null) { methodLocation = MethodLocation.elementInClass(methodLocation.getPsiElement(), containingClass); } } return methodLocation; }
Example #6
Source File: GetterFieldProcessor.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 6 votes |
@NotNull public PsiMethod createGetterMethod(@NotNull PsiField psiField, @NotNull PsiClass psiClass, @NotNull String methodModifier) { final String methodName = LombokUtils.getGetterName(psiField); LombokLightMethodBuilder methodBuilder = new LombokLightMethodBuilder(psiField.getManager(), methodName) .withMethodReturnType(psiField.getType()) .withContainingClass(psiClass) .withNavigationElement(psiField); if (StringUtil.isNotEmpty(methodModifier)) { methodBuilder.withModifier(methodModifier); } boolean isStatic = psiField.hasModifierProperty(PsiModifier.STATIC); if (isStatic) { methodBuilder.withModifier(PsiModifier.STATIC); } final String blockText = String.format("return %s.%s;", isStatic ? psiClass.getName() : "this", psiField.getName()); methodBuilder.withBody(PsiMethodUtil.createCodeBlockFromText(blockText, methodBuilder)); PsiModifierList modifierList = methodBuilder.getModifierList(); copyAnnotations(psiField, modifierList, LombokUtils.NON_NULL_PATTERN, LombokUtils.NULLABLE_PATTERN, LombokUtils.DEPRECATED_PATTERN); addOnXAnnotations(PsiAnnotationSearchUtil.findAnnotation(psiField, Getter.class), modifierList, "onMethod"); return methodBuilder; }
Example #7
Source File: BlazeJavaTestMethodConfigurationProducerTest.java From intellij with Apache License 2.0 | 6 votes |
@Test public void testConfigWithDifferentFilterIgnored() { // Arrange PsiMethod method = setupGenericJunitTestClassAndBlazeTarget(); ConfigurationContext context = createContextFromPsi(method); BlazeCommandRunConfiguration config = (BlazeCommandRunConfiguration) context.getConfiguration().getConfiguration(); BlazeCommandRunConfigurationCommonState handlerState = config.getHandlerStateIfType(BlazeCommandRunConfigurationCommonState.class); // modify the test filter, and check that is enough for the producer to class it as different. List<String> flags = new ArrayList<>(handlerState.getBlazeFlagsState().getRawFlags()); flags.removeIf((flag) -> flag.startsWith(BlazeFlags.TEST_FILTER)); flags.add(BlazeFlags.TEST_FILTER + "=com.google.test.DifferentTestClass#"); handlerState.getBlazeFlagsState().setRawFlags(flags); // Act boolean isConfigFromContext = new TestContextRunConfigurationProducer().doIsConfigFromContext(config, context); // Assert assertThat(isConfigFromContext).isFalse(); }
Example #8
Source File: ComponentsMethodDeclarationHandler.java From litho with Apache License 2.0 | 6 votes |
@Override public PsiElement[] getGotoDeclarationTargets( @Nullable PsiElement sourceElement, int offset, Editor editor) { // Exclusions if (sourceElement == null || PsiTreeUtil.getParentOfType(sourceElement, PsiImportStatement.class) != null) { return PsiElement.EMPTY_ARRAY; } final Project project = sourceElement.getProject(); return BaseLithoComponentsDeclarationHandler.resolve(sourceElement) // Filter Methods .filter(PsiMethod.class::isInstance) .map(PsiMethod.class::cast) .map(method -> findSpecMethods(method, project)) .findFirst() .map( result -> { final Map<String, String> data = new HashMap<>(); data.put(EventLogger.KEY_TARGET, "method"); data.put(EventLogger.KEY_TYPE, EventLogger.VALUE_NAVIGATION_TYPE_GOTO); LOGGER.log(EventLogger.EVENT_NAVIGATION, data); return result; }) .orElse(PsiMethod.EMPTY_ARRAY); }
Example #9
Source File: GodClassPreviewResultDialog.java From IntelliJDeodorant with MIT License | 6 votes |
@Override public int getChildCount(Object parent) { if (parent instanceof PsiMethodComparingPair) { PsiMethod initialMethod = ((PsiMethodComparingPair) parent).getInitialPsiMethod(); List<PsiElementComparingPair> children = previewProcessor.getMethodElementsComparingMap().get(initialMethod); if (children != null) { return children.size(); } else { return 0; } } else if (parent instanceof PsiElementComparingPair) { return 0; } else if (parent == previewProcessor.getExtractedClass()) { return 0; } else if (parent instanceof PsiClassWrapper) { return previewProcessor.getMethodComparingList().size() + previewProcessor.getPsiElementChanges().size(); } else if (parent instanceof PsiElementChange) { return 0; } return 2; //source and extracted class }
Example #10
Source File: ConstructorInjectToProvidesHandler.java From dagger-intellij-plugin with Apache License 2.0 | 6 votes |
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; }
Example #11
Source File: RefactorSetterHandler.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override protected void process(List<ClassMember> classMembers) { for (ClassMember classMember : classMembers) { final PsiElementClassMember elementClassMember = (PsiElementClassMember) classMember; PsiField psiField = (PsiField) elementClassMember.getPsiElement(); PsiMethod psiMethod = PropertyUtil.findPropertySetter(psiField.getContainingClass(), psiField.getName(), false, false); if (null != psiMethod) { PsiModifierList modifierList = psiField.getModifierList(); if (null != modifierList) { PsiAnnotation psiAnnotation = modifierList.addAnnotation(Setter.class.getName()); psiMethod.delete(); } } } }
Example #12
Source File: StatePropCompletionContributor.java From litho with Apache License 2.0 | 6 votes |
static void addCompletionResult( @NotNull CompletionResultSet completionResultSet, PsiMethod currentMethod, PsiMethod[] allMethods, Predicate<PsiParameter> annotationCheck) { // Don't propose completion with current method parameters Set<String> excludingParameters = Stream.of(currentMethod.getParameterList().getParameters()) .filter(annotationCheck) .map(PsiParameter::getName) .filter(Objects::nonNull) .collect(Collectors.toSet()); LithoPluginUtils.getPsiParameterStream(currentMethod, allMethods) .filter(annotationCheck) .filter(parameter -> !excludingParameters.contains(parameter.getName())) .map(StatePropCompletionContributor::createCompletionResult) .forEach(completionResultSet::addElement); }
Example #13
Source File: OnEventGenerateUtils.java From litho with Apache License 2.0 | 6 votes |
/** * 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()); }
Example #14
Source File: TestMethodSelectionUtil.java From intellij with Apache License 2.0 | 6 votes |
/** * Get all test methods directly or indirectly selected in the given context. This includes * methods selected in the Structure panel, as well as methods the context location is inside of. * * @param context The context to get selected test methods from. * @param allMustMatch If true, will return null if any selected elements are not test methods. * @return A list of test methods (with at least one element), or null if: * <ul> * <li>There are no selected test methods * <li>{@code allMustMatch} is true, but elements other than test methods are selected * </ul> * * @see #getDirectlySelectedMethods(ConfigurationContext, boolean) * @see #getIndirectlySelectedMethod(ConfigurationContext) */ @Nullable public static List<PsiMethod> getSelectedMethods( @NotNull ConfigurationContext context, boolean allMustMatch) { List<PsiMethod> directlySelectedMethods = getDirectlySelectedMethods(context, allMustMatch); if (directlySelectedMethods != null && directlySelectedMethods.size() > 0) { return directlySelectedMethods; } if (allMustMatch && JUnitConfigurationUtil.isMultipleElementsSelected(context)) { return null; } PsiMethod indirectlySelectedMethod = getIndirectlySelectedMethod(context); if (indirectlySelectedMethod != null) { return Collections.singletonList(indirectlySelectedMethod); } return null; }
Example #15
Source File: BuckTestDetector.java From buck with Apache License 2.0 | 6 votes |
/** * Returns true if the given method is one of the kind of tests that Buck knows how to run. * (Currently, JUnit3, JUnit4, and TestNG.) * * <p>Note that this is merely a syntactic check that makes no guarantee that the method appears * in a file that is part of a buck test target (or even a buck cell). */ public static boolean isTestMethod(PsiMethod psiMethod) { PsiClass psiClass = psiMethod.getContainingClass(); if (psiClass == null) { return false; } if (isJUnit3TestCaseClass(psiClass)) { return isJUnit3TestMethod(psiMethod); } if (isAnnotatedJUnit4TestClass(psiClass)) { return isJUnit4TestMethod(psiMethod); } if (isPotentialJUnit4TestClass(psiClass) && isJUnit4TestMethod(psiMethod)) { return true; } if (isPotentialTestNGTestClass(psiClass) && isTestNGTestMethod(psiMethod)) { return true; } return false; }
Example #16
Source File: SetterFieldProcessor.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 6 votes |
private boolean validateExistingMethods(@NotNull PsiField psiField, @NotNull ProblemBuilder builder) { boolean result = true; final PsiClass psiClass = psiField.getContainingClass(); if (null != psiClass) { final Collection<PsiMethod> classMethods = PsiClassUtil.collectClassMethodsIntern(psiClass); filterToleratedElements(classMethods); final boolean isBoolean = PsiType.BOOLEAN.equals(psiField.getType()); final Collection<String> methodNames = getAllSetterNames(psiField, isBoolean); for (String methodName : methodNames) { if (PsiMethodUtil.hasSimilarMethod(classMethods, methodName, 1)) { final String setterMethodName = getSetterName(psiField, isBoolean); builder.addWarning("Not generated '%s'(): A method with similar name '%s' already exists", setterMethodName, methodName); result = false; } } } return result; }
Example #17
Source File: SqliteMagicStructureViewExtension.java From sqlitemagic with Apache License 2.0 | 6 votes |
@Override public StructureViewTreeElement[] getChildren(PsiElement parent) { Collection<StructureViewTreeElement> result = new ArrayList<StructureViewTreeElement>(); final PsiClass psiClass = (PsiClass) parent; for (PsiField psiField : psiClass.getFields()) { if (psiField instanceof SqliteMagicLightFieldBuilder) { result.add(new PsiFieldTreeElement(psiField, false)); } } for (PsiMethod psiMethod : psiClass.getMethods()) { if (psiMethod instanceof SqliteMagicLightMethodBuilder) { result.add(new PsiMethodTreeElement(psiMethod, false)); } } if (!result.isEmpty()) { return result.toArray(new StructureViewTreeElement[result.size()]); } else { return StructureViewTreeElement.EMPTY_ARRAY; } }
Example #18
Source File: HaxeMethodUtils.java From intellij-haxe with Apache License 2.0 | 6 votes |
@NotNull private static PsiMethod[] findSuperMethodsInternal(PsiMethod method, PsiClass parentClass) { if (null == parentClass || null == method) return PsiMethod.EMPTY_ARRAY; List<PsiMethod> sooperMethods = new ArrayList<PsiMethod>(); LinkedList<PsiClass> soopers = new LinkedList<PsiClass>(Arrays.asList(parentClass.getSupers())); while (!soopers.isEmpty()) { PsiClass sooper = soopers.pollFirst(); // Get the super-method on the closest superclass that contains the method. PsiMethod sooperMethod = MethodSignatureUtil.findMethodBySignature(sooper, method, true); if (null != sooperMethod) { sooperMethods.add(sooperMethod); soopers.addAll(Arrays.asList(sooperMethod.getContainingClass().getSupers())); } } return sooperMethods.toArray(PsiMethod.EMPTY_ARRAY); }
Example #19
Source File: LayoutSpecMethodParameterAnnotationsContributor.java From litho with Apache License 2.0 | 5 votes |
private static Optional<Set<String>> getParameterAnnotations(PsiMethod method) { return Arrays.stream(method.getAnnotations()) .map(PsiAnnotation::getQualifiedName) .map(LAYOUT_SPEC_DELEGATE_METHOD_TO_PARAMETER_ANNOTATIONS::get) .filter(Objects::nonNull) .findAny(); }
Example #20
Source File: LithoPluginUtils.java From litho with Apache License 2.0 | 5 votes |
/** @return the Stream of unique parameters from all methods excluding current method. */ public static Stream<PsiParameter> getPsiParameterStream( @Nullable PsiMethod currentMethod, PsiMethod[] allMethods) { return Stream.of(allMethods) .filter(psiMethod -> !psiMethod.equals(currentMethod)) .map(PsiMethod::getParameterList) .map(PsiParameterList::getParameters) .flatMap(Stream::of) .filter(distinctByKey(PsiParameter::getName)); }
Example #21
Source File: IdeaUtils.java From camel-idea-plugin with Apache License 2.0 | 5 votes |
/** * Is the element from a constructor call with the given constructor name (eg class name) * * @param element the element * @param constructorName the name of the constructor (eg class) * @return <tt>true</tt> if its a constructor call from the given name, <tt>false</tt> otherwise */ public boolean isElementFromConstructor(@NotNull PsiElement element, @NotNull String constructorName) { // java constructor PsiConstructorCall call = PsiTreeUtil.getParentOfType(element, PsiConstructorCall.class); if (call != null) { PsiMethod resolved = call.resolveConstructor(); if (resolved != null) { return constructorName.equals(resolved.getName()); } } return false; }
Example #22
Source File: TemplateServiceTest.java From litho with Apache License 2.0 | 5 votes |
@Test public void getMethodTemplate() { ApplicationManager.getApplication() .invokeAndWait( () -> { final Project project = testHelper.getFixture().getProject(); final PsiMethod onAttached = ServiceManager.getService(project, TemplateService.class) .getMethodTemplate("OnAttached", project); assertThat(onAttached).isNotNull(); }); }
Example #23
Source File: DocGenerateAction.java From CodeMaker with Apache License 2.0 | 5 votes |
/** * Generate method params type string. * * @param psiMethod the psi method * @return the string */ private String generateMethodParamsType(PsiMethod psiMethod) { StringBuilder stringBuilder = new StringBuilder(); for (PsiParameter psiParameter : psiMethod.getParameterList().getParameters()) { stringBuilder.append(psiParameter.getType().getCanonicalText()).append(", "); } if (stringBuilder.toString().endsWith(", ")) { stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length() - 1); } return stringBuilder.toString(); }
Example #24
Source File: TemplateService.java From litho with Apache License 2.0 | 5 votes |
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); }
Example #25
Source File: CamelRouteLineMarkerProvider.java From camel-idea-plugin with Apache License 2.0 | 5 votes |
private boolean isRouteStartIdentifier(PsiIdentifier identifier, PsiElement resolvedIdentifier) { // Eval methods from parent PsiMethodCallExpression to exclude start route method (from) PsiElement element = identifier; if (resolvedIdentifier instanceof PsiMethod) { element = PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression.class); } if (element == null) { return false; } return getCamelIdeaUtils().isCamelRouteStartExpression(element); }
Example #26
Source File: DaggerUseScopeEnlarger.java From intellij with Apache License 2.0 | 5 votes |
/** Returns true if the method is called in generated code. */ static boolean isImplicitUsageMethod(PsiElement element) { if (!(element instanceof PsiMethod)) { return false; } PsiMethod method = (PsiMethod) element; if (method.hasModifierProperty(PsiModifier.PRIVATE)) { return false; } PsiModifierList modifiers = method.getModifierList(); return IMPLICIT_METHOD_USAGE_ANNOTATIONS .stream() .anyMatch(s -> modifiers.findAnnotation(s) != null); }
Example #27
Source File: JavaMethodUtils.java From camel-idea-plugin with Apache License 2.0 | 5 votes |
/** * Return all method names for the specific class and it's super classes, except * Object and Class */ public Collection<PsiMethod> getMethods(PsiClass psiClass) { return Stream.of(psiClass.getAllMethods()) .filter(p -> !p.isConstructor()) .filter(p -> !Object.class.getName().equals(p.getContainingClass().getQualifiedName())) .filter(p -> !Class.class.getName().equals(p.getContainingClass().getQualifiedName())) .collect(Collectors.toCollection(ArrayList::new)); }
Example #28
Source File: QuarkusKubernetesProvider.java From intellij-quarkus with Eclipse Public License 2.0 | 5 votes |
private void collectProperties(String prefix, PsiClass configType, IPropertiesCollector collector, IPsiUtils utils, DocumentFormat documentFormat) { String sourceType = configType.getQualifiedName(); PsiMethod[] methods = configType.getMethods(); for (PsiMethod method : methods) { String resultTypeName = PsiTypeUtils.getResolvedResultTypeName(method); PsiClass resultTypeClass = PsiTypeUtils.findType(method.getManager(), resultTypeName); String methodName = method.getName(); String propertyName = prefix + "." + StringUtil.hyphenate(methodName); boolean isArray = method.getReturnType().getArrayDimensions() > 0; if (isArray) { propertyName += "[*]"; } if (isSimpleFieldType(resultTypeClass, resultTypeName)) { String type = getPropertyType(resultTypeClass, resultTypeName); String description = utils.getJavadoc(method, documentFormat); String sourceMethod = getSourceMethod(method); String defaultValue = PsiTypeUtils.getDefaultValue(method); String extensionName = null; super.updateHint(collector, resultTypeClass); super.addItemMetadata(collector, propertyName, type, description, sourceType, null, sourceMethod, defaultValue, extensionName, PsiTypeUtils.isBinary(method)); } else { collectProperties(propertyName, resultTypeClass, collector, utils, documentFormat); } } }
Example #29
Source File: AbstractMethodProcessor.java From sqlitemagic with Apache License 2.0 | 5 votes |
@NotNull @Override public Collection<SqliteMagicProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) { Collection<SqliteMagicProblem> result = Collections.emptyList(); PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class); if (null != psiMethod) { ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(); validate(psiAnnotation, psiMethod, problemNewBuilder); result = problemNewBuilder.getProblems(); } return result; }
Example #30
Source File: LombokToStringHandler.java From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void processClass(@NotNull PsiClass psiClass) { final PsiElementFactory factory = JavaPsiFacade.getElementFactory(psiClass.getProject()); final PsiClassType stringClassType = factory.createTypeByFQClassName(CommonClassNames.JAVA_LANG_STRING, psiClass.getResolveScope()); final PsiMethod toStringMethod = findPublicNonStaticMethod(psiClass, "toString", stringClassType); if (null != toStringMethod) { toStringMethod.delete(); } addAnnotation(psiClass, ToString.class); }