com.intellij.psi.PsiClassType Java Examples

The following examples show how to use com.intellij.psi.PsiClassType. 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: MapClassMetadata.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
private void init(Module module, PsiClassType type) {
  if (isValidType(type)) {
    Map<PsiTypeParameter, PsiType> typeParameterToResolvedType = getTypeParameters(type);
    assert typeParameterToResolvedType != null;
    Set<PsiTypeParameter> typeParameterKetSet = typeParameterToResolvedType.keySet();
    Optional<PsiTypeParameter> keyTypeParam =
        typeParameterKetSet.stream().filter(v -> requireNonNull(v.getName()).equals("K"))
            .findFirst();
    Optional<PsiTypeParameter> valueTypeParam =
        typeParameterKetSet.stream().filter(v -> requireNonNull(v.getName()).equals("V"))
            .findFirst();
    if (keyTypeParam.isPresent()) {
      this.keyType = typeParameterToResolvedType.get(keyTypeParam.get());
      if (this.keyType != null) {
        keyMetadataProxy = newMetadataProxy(module, this.keyType);
      }
    }

    if (valueTypeParam.isPresent()) {
      this.valueType = typeParameterToResolvedType.get(valueTypeParam.get());
      if (this.valueType != null) {
        valueMetadataProxy = newMetadataProxy(module, this.valueType);
      }
    }
  }
}
 
Example #2
Source File: OttoLineMarkerProvider.java    From otto-intellij-plugin with Apache License 2.0 6 votes vote down vote up
@Override public void navigate(final MouseEvent mouseEvent, final PsiElement psiElement) {
  PsiMethod subscribeMethod = (PsiMethod) psiElement;
  final PsiTypeElement parameterTypeElement = getMethodParameter(subscribeMethod);
  final SubscriberMetadata subscriberMetadata = SubscriberMetadata.getSubscriberMetadata(subscribeMethod);
  if ((parameterTypeElement.getType() instanceof PsiClassType) && (subscriberMetadata != null)) {
    final PsiClass eventClass = ((PsiClassType) parameterTypeElement.getType()).resolve();
    PickAction.startPicker(subscriberMetadata.displayedTypesOnSubscriberMethods(),
        new RelativePoint(mouseEvent), new PickAction.Callback() {

      @Override public void onTypeChose(PickAction.Type type) {
        if (type.equals(PickAction.Type.PRODUCER)) {
          new ShowUsagesAction(PRODUCERS).startFindUsages(eventClass,
              new RelativePoint(mouseEvent), PsiUtilBase.findEditor(psiElement),
              MAX_USAGES);
        } else if (type.equals(PickAction.Type.EVENT_POST)) {
          PsiMethod ottoBusMethod = subscriberMetadata.getBusPostMethod(psiElement.getProject());
          new ShowUsagesAction(new BusPostDecider(eventClass)).startFindUsages(
              ottoBusMethod, new RelativePoint(mouseEvent),
              PsiUtilBase.findEditor(psiElement), MAX_USAGES);
        }
      }
    });
  }
}
 
Example #3
Source File: ClassSuggestionNodeFactory.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
@NotNull
public static MetadataProxy newMetadataProxy(Module module, @NotNull PsiType type) {
  if (type instanceof PsiArrayType) {
    return new ArrayMetadataProxy(module, (PsiArrayType) type);
  } else if (type instanceof PsiPrimitiveType) {
    PsiPrimitiveType primitiveType = (PsiPrimitiveType) type;
    type = getBoxedTypeFromPrimitiveType(module, primitiveType);
  }

  if (type instanceof PsiClassType) {
    SuggestionNodeType suggestionNodeType = getSuggestionNodeType(type);
    if (suggestionNodeType == SuggestionNodeType.MAP) {
      return new MapClassMetadataProxy((PsiClassType) type);
    } else {
      return new ClassMetadataProxy((PsiClassType) type);
    }
  }

  throw new IllegalAccessError(
      "Supports only PsiArrayType, PsiPrimitiveType & PsiClassType types");
}
 
Example #4
Source File: PsiUtils.java    From data-mediator with Apache License 2.0 6 votes vote down vote up
/**
 * Resolves generics on the given type and returns them (if any) or null if there are none
 */
public static List<PsiType> getResolvedGenerics(PsiType type) {
    List<PsiType> psiTypes = null;

    if (type instanceof PsiClassType) {
        PsiClassType pct = (PsiClassType) type;
        psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());
    }

    return psiTypes;
}
 
Example #5
Source File: PsiTypeUtils.java    From litho with Apache License 2.0 6 votes vote down vote up
static TypeName getTypeName(PsiType type) {
  if (type instanceof PsiPrimitiveType) {
    // float
    return getPrimitiveTypeName((PsiPrimitiveType) type);
  } else if (type instanceof PsiClassType && ((PsiClassType) type).getParameterCount() > 0) {
    // Set<Integer>
    PsiClassType classType = (PsiClassType) type;
    return ParameterizedTypeName.get(
        guessClassName(classType.rawType().getCanonicalText()),
        getTypeNameArray(classType.getParameters()));
  } else if (type instanceof PsiArrayType) {
    // int[]
    PsiType componentType = ((PsiArrayType) type).getComponentType();
    return ArrayTypeName.of(getTypeName(componentType));
  } else if (type.getCanonicalText().contains("?")) {
    // ? extends Type
    return getWildcardTypeName(type.getCanonicalText());
  } else {
    return guessClassName(type.getCanonicalText());
  }
}
 
Example #6
Source File: PsiTypeVariablesExtractor.java    From litho with Apache License 2.0 6 votes vote down vote up
public static ImmutableList<TypeVariableName> getTypeVariables(PsiClass psiClass) {
  PsiTypeParameter[] psiTypeParameters = psiClass.getTypeParameters();

  final List<TypeVariableName> typeVariables = new ArrayList<>(psiTypeParameters.length);
  for (PsiTypeParameter psiTypeParameter : psiTypeParameters) {
    final PsiReferenceList extendsList = psiTypeParameter.getExtendsList();
    final PsiClassType[] psiClassTypes = extendsList.getReferencedTypes();

    final TypeName[] boundsTypeNames = new TypeName[psiClassTypes.length];
    for (int i = 0, size = psiClassTypes.length; i < size; i++) {
      boundsTypeNames[i] = PsiTypeUtils.getTypeName(psiClassTypes[i]);
    }

    final TypeVariableName typeVariable =
        TypeVariableName.get(psiTypeParameter.getName(), boundsTypeNames);
    typeVariables.add(typeVariable);
  }

  return ImmutableList.copyOf(typeVariables);
}
 
Example #7
Source File: PsiCustomUtil.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
@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;
  }
}
 
Example #8
Source File: TypeParametersTranslator.java    From java2typescript with Apache License 2.0 6 votes vote down vote up
public static String print(PsiTypeParameter[] parameters, TranslationContext ctx) {
    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < parameters.length; i++) {
        PsiTypeParameter p = parameters[i];
        builder.append(p.getName());
        PsiClassType[] extensions = p.getExtendsList().getReferencedTypes();
        if (extensions.length > 0) {
            builder.append(" extends ");
            for (PsiClassType ext : extensions) {
                builder.append(TypeHelper.printType(ext, ctx));
            }
        }
        if (i != parameters.length - 1) {
            builder.append(", ");
        }
    }
    return builder.toString();
}
 
Example #9
Source File: EnumClassMetadata.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
private void init(@NotNull PsiClassType type) {
  if (isValidType(type)) {
    PsiField[] fields = requireNonNull(toValidPsiClass(type)).getFields();
    List<PsiField> acceptableFields = new ArrayList<>();
    for (PsiField field : fields) {
      if (field != null && field.getType().equals(type)) {
        acceptableFields.add(field);
      }
    }
    if (acceptableFields.size() != 0) {
      childLookup = new THashMap<>();
      childrenTrie = new PatriciaTrie<>();
      acceptableFields.forEach(field -> {
        childLookup.put(sanitise(requireNonNull(field.getName())), field);
        childrenTrie.put(sanitise(field.getName()), field);
      });
    }
  } else {
    childLookup = null;
    childrenTrie = null;
  }
}
 
Example #10
Source File: CodeGenerator.java    From ParcelablePlease with Apache License 2.0 6 votes vote down vote up
/**
 * Make the class implementing Parcelable
 */
private void makeClassImplementParcelable(PsiElementFactory elementFactory, JavaCodeStyleManager styleManager) {
  final PsiClassType[] implementsListTypes = psiClass.getImplementsListTypes();
  final String implementsType = "android.os.Parcelable";

  for (PsiClassType implementsListType : implementsListTypes) {
    PsiClass resolved = implementsListType.resolve();

    // Already implements Parcelable, no need to add it
    if (resolved != null && implementsType.equals(resolved.getQualifiedName())) {
      return;
    }
  }

  PsiJavaCodeReferenceElement implementsReference =
      elementFactory.createReferenceFromText(implementsType, psiClass);
  PsiReferenceList implementsList = psiClass.getImplementsList();

  if (implementsList != null) {
    styleManager.shortenClassReferences(implementsList.add(implementsReference));
  }
}
 
Example #11
Source File: CleanupProcessor.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void validateCleanUpMethodExists(@NotNull PsiLocalVariable psiVariable, @NotNull String cleanupName, @NotNull ProblemNewBuilder problemNewBuilder) {
  final PsiType psiType = psiVariable.getType();
  if (psiType instanceof PsiClassType) {
    final PsiClassType psiClassType = (PsiClassType) psiType;
    final PsiClass psiClassOfField = psiClassType.resolve();
    final PsiMethod[] methods;

    if (psiClassOfField != null) {
      methods = psiClassOfField.findMethodsByName(cleanupName, true);
      boolean hasCleanupMethod = false;
      for (PsiMethod method : methods) {
        if (0 == method.getParameterList().getParametersCount()) {
          hasCleanupMethod = true;
        }
      }

      if (!hasCleanupMethod) {
        problemNewBuilder.addError("'@Cleanup': method '%s()' not found on target class", cleanupName);
      }
    }
  } else {
    problemNewBuilder.addError("'@Cleanup': is legal only on a local variable declaration inside a block");
  }
}
 
Example #12
Source File: PsiCustomUtil.java    From intellij-spring-assistant with MIT License 6 votes vote down vote up
public static boolean isValidType(@NotNull PsiType type) {
  if (!type.isValid()) {
    TimeoutUtil.sleep(
        1); // to see if processing in another thread suddenly makes the type valid again (which is a bug)
    if (!type.isValid()) {
      return false;
    }
  }
  if (type instanceof PsiArrayType) {
    return isValidType(PsiArrayType.class.cast(type).getComponentType());
  } else if (type instanceof PsiWildcardType) {
    PsiType bound = ((PsiWildcardType) type).getBound();
    return bound != null && isValidType(bound);
  } else if (type instanceof PsiCapturedWildcardType) {
    PsiType lowerBound = ((PsiCapturedWildcardType) type).getLowerBound();
    type = (lowerBound != NULL ? lowerBound : ((PsiCapturedWildcardType) type).getUpperBound());
    return type != NULL && isValidType(type);
  } else if (type instanceof PsiClassType) {
    PsiClassType.ClassResolveResult classResolveResult = ((PsiClassType) type).resolveGenerics();
    return classResolveResult.isValidResult() && isValidElement(
        requireNonNull(classResolveResult.getElement())) && !hasUnresolvedComponents(type);
  }
  return true;
}
 
Example #13
Source File: ConstructorInjectToProvidesHandler.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
private void showUsages(final MouseEvent mouseEvent, final PsiParameter psiParameter) {
  // Check to see if class type of psiParameter has constructor with @Inject. Otherwise, proceed.
  if (navigateToConstructorIfProvider(psiParameter)) {
    return;
  }

  // If psiParameter is Set<T>, check if @Provides(type=SET) T providesT exists.
  // Also check map (TODO(radford): Add check for map).

  List<PsiType> paramTypes = PsiConsultantImpl.getTypeParameters(psiParameter);
  if (paramTypes.isEmpty()) {
    new ShowUsagesAction(
        new Decider.ConstructorParameterInjectDecider(psiParameter)).startFindUsages(
        PsiConsultantImpl.checkForLazyOrProvider(psiParameter),
        new RelativePoint(mouseEvent),
        PsiUtilBase.findEditor(psiParameter), MAX_USAGES);
  } else {
    ShowUsagesAction actions = new ShowUsagesAction(
        new Decider.CollectionElementParameterInjectDecider(psiParameter));
    actions.setListener(new ShowUsagesAction.Listener() {
      @Override public void onFinished(boolean hasResults) {
        if (!hasResults) {
          new ShowUsagesAction(
              new Decider.ConstructorParameterInjectDecider(psiParameter)).startFindUsages(
              PsiConsultantImpl.checkForLazyOrProvider(psiParameter),
              new RelativePoint(mouseEvent),
              PsiUtilBase.findEditor(psiParameter), MAX_USAGES);
        }
      }
    });

    actions.startFindUsages(((PsiClassType) paramTypes.get(0)).resolve(),
        new RelativePoint(mouseEvent),
        PsiUtilBase.findEditor(psiParameter), MAX_USAGES);
  }
}
 
Example #14
Source File: OttoLineMarkerProvider.java    From otto-intellij-plugin with Apache License 2.0 5 votes vote down vote up
@Override public void navigate(MouseEvent mouseEvent, PsiElement psiElement) {
  if (psiElement instanceof PsiMethod) {
    PsiMethod psiMethod = (PsiMethod) psiElement;
    PsiTypeElement returnTypeElement = psiMethod.getReturnTypeElement();
    PsiClass eventClass = ((PsiClassType) returnTypeElement.getType()).resolve();

    new ShowUsagesAction(SUBSCRIBERS).startFindUsages(eventClass,
        new RelativePoint(mouseEvent), PsiUtilBase.findEditor(returnTypeElement),
        MAX_USAGES);
  }
}
 
Example #15
Source File: PsiUtils.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static String getNonGenericType(PsiType type) {
    if (type instanceof PsiClassType) {
        PsiClassType pct = (PsiClassType) type;
        final PsiClass psiClass = pct.resolve();

        return psiClass != null ? psiClass.getQualifiedName() : null;
    }

    return type.getCanonicalText();
}
 
Example #16
Source File: PsiUtils.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Resolves generics on the given type and returns them (if any) or null if there are none
 *
 * @param type
 * @return
 */
public static List<PsiType> getResolvedGenerics(PsiType type) {
    List<PsiType> psiTypes = null;

    if (type instanceof PsiClassType) {
        PsiClassType pct = (PsiClassType) type;
        psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());
    }

    return psiTypes;
}
 
Example #17
Source File: PsiUtils.java    From android-parcelable-intellij-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Checks that the given type is an implementer of the given canonicalName with the given typed parameters
 *
 * @param type                what we're checking against
 * @param canonicalName       the type must extend/implement this generic
 * @param canonicalParamNames the type that the generic(s) must be (in this order)
 * @return
 */
public static boolean isTypedClass(PsiType type, String canonicalName, String... canonicalParamNames) {
    PsiClass parameterClass = PsiTypesUtil.getPsiClass(type);

    if (parameterClass == null) {
        return false;
    }

    // This is a safe cast, for if parameterClass != null, the type was checked in PsiTypesUtil#getPsiClass(...)
    PsiClassType pct = (PsiClassType) type;

    // Main class name doesn't match; exit early
    if (!canonicalName.equals(parameterClass.getQualifiedName())) {
        return false;
    }

    List<PsiType> psiTypes = new ArrayList<PsiType>(pct.resolveGenerics().getSubstitutor().getSubstitutionMap().values());

    for (int i = 0; i < canonicalParamNames.length; i++) {
        if (!isOfType(psiTypes.get(i), canonicalParamNames[i])) {
            return false;
        }
    }

    // Passed all screenings; must be a match!
    return true;
}
 
Example #18
Source File: LombokToStringHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example #19
Source File: PsiConsultantImpl.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
private static PsiClassType getPsiClassType(PsiElement psiElement) {
  if (psiElement instanceof PsiVariable) {
    return (PsiClassType) ((PsiVariable) psiElement).getType();
  } else if (psiElement instanceof PsiMethod) {
    return (PsiClassType) ((PsiMethod) psiElement).getReturnType();
  }
  return null;
}
 
Example #20
Source File: PsiConsultantImpl.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static PsiClass checkForLazyOrProvider(PsiField psiField) {
  PsiClass wrapperClass = PsiConsultantImpl.getClass(psiField);

  PsiType psiFieldType = psiField.getType();
  if (!(psiFieldType instanceof PsiClassType)) {
    return wrapperClass;
  }

  return getPsiClass(wrapperClass, psiFieldType);
}
 
Example #21
Source File: CamelDocumentationProvider.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public String getQuickNavigateInfo(PsiElement element, PsiElement originalElement) {
    if (ServiceManager.getService(element.getProject(), CamelService.class).isCamelPresent()) {
        PsiExpressionList exps = PsiTreeUtil.getNextSiblingOfType(originalElement, PsiExpressionList.class);
        if (exps != null) {
            if (exps.getExpressions().length >= 1) {
                // grab first string parameter (as the string would contain the camel endpoint uri
                final PsiClassType stringType = PsiType.getJavaLangString(element.getManager(), element.getResolveScope());
                PsiExpression exp = Arrays.stream(exps.getExpressions()).filter(
                    e -> e.getType() != null && stringType.isAssignableFrom(e.getType()))
                    .findFirst().orElse(null);
                if (exp instanceof PsiLiteralExpression) {
                    Object o = ((PsiLiteralExpression) exp).getValue();
                    String val = o != null ? o.toString() : null;
                    // okay only allow this popup to work when its from a RouteBuilder class
                    PsiClass clazz = PsiTreeUtil.getParentOfType(originalElement, PsiClass.class);
                    if (clazz != null) {
                        PsiClassType[] types = clazz.getExtendsListTypes();
                        boolean found = Arrays.stream(types).anyMatch(p -> p.getClassName().equals("RouteBuilder"));
                        if (found) {
                            String componentName = asComponentName(val);
                            if (componentName != null) {
                                // the quick info cannot be so wide so wrap at 120 chars
                                return generateCamelComponentDocumentation(componentName, val, 120, element.getProject());
                            }
                        }
                    }
                }
            }
        }
    }

    return null;
}
 
Example #22
Source File: PsiConsultantImpl.java    From dagger-intellij-plugin with Apache License 2.0 5 votes vote down vote up
public static List<PsiType> getTypeParameters(PsiElement psiElement) {
  PsiClassType psiClassType = getPsiClassType(psiElement);
  if (psiClassType == null) {
    return new ArrayList<PsiType>();
  }

  // Check if @Provides(type=?) pattern (annotation with specified type).
  PsiAnnotationMemberValue attribValue = findTypeAttributeOfProvidesAnnotation(psiElement);
  if (attribValue != null) {
    if (attribValue.textMatches(SET_TYPE)) {
      // type = SET. Transform the type parameter to the element type.
      ArrayList<PsiType> result = new ArrayList<PsiType>();
      result.add(psiClassType);
      return result;
    } else if (attribValue.textMatches(MAP_TYPE)) {
      // TODO(radford): Need to figure out key type for maps.
      // type = SET or type = MAP. Transform the type parameter to the element type.
      //ArrayList<PsiType> result = new ArrayList<PsiType>();
      //result.add(psiKeyType):
      //result.add(psiClassType);
      //return result;
    }
  }

  if (PsiConsultantImpl.isLazyOrProvider(getClass(psiClassType))) {
    psiClassType = extractFirstTypeParameter(psiClassType);
  }

  Collection<PsiType> typeParameters =
      psiClassType.resolveGenerics().getSubstitutor().getSubstitutionMap().values();
  return new ArrayList<PsiType>(typeParameters);
}
 
Example #23
Source File: SneakyThrowsExceptionHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean isHandled(@Nullable PsiElement element, @NotNull PsiClassType exceptionType, PsiElement topElement) {
  if (!(topElement instanceof PsiCodeBlock)) {
    final PsiMethod psiMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
    return psiMethod != null && isExceptionHandled(psiMethod, exceptionType);
  }
  return false;
}
 
Example #24
Source File: SynchronizedProcessor.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@NotNull
@Override
public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) {
  final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(2);

  PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class);
  if (null != psiMethod) {
    if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
      problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.",
        PsiQuickFixFactory.createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false)
      );
    }

    final String lockFieldName = PsiAnnotationUtil.getStringAnnotationValue(psiAnnotation, "value");
    if (StringUtil.isNotEmpty(lockFieldName)) {
      final PsiClass containingClass = psiMethod.getContainingClass();

      if (null != containingClass) {
        final PsiField lockField = containingClass.findFieldByName(lockFieldName, true);
        if (null != lockField) {
          if (!lockField.hasModifierProperty(PsiModifier.FINAL)) {
            problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName),
              PsiQuickFixFactory.createModifierListFix(lockField, PsiModifier.FINAL, true, false));
          }
        } else {
          final PsiClassType javaLangObjectType = PsiType.getJavaLangObject(containingClass.getManager(), containingClass.getResolveScope());

          problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName),
            PsiQuickFixFactory.createNewFieldFix(containingClass, lockFieldName, javaLangObjectType, "new Object()", PsiModifier.PRIVATE, PsiModifier.FINAL));
        }
      }
    }
  } else {
    problemNewBuilder.addError("'@Synchronized' is legal only on methods.");
  }

  return problemNewBuilder.getProblems();
}
 
Example #25
Source File: IntroduceLombokVariableHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private IntroduceVariableSettings getIntroduceVariableSettings(Project project, IntroduceVariableSettings variableSettings) {
  final PsiClassType psiClassType = PsiType.getTypeByName(selectedTypeFQN, project, GlobalSearchScope.projectScope(project));
  if (null != psiClassType) {
    return new IntroduceVariableSettingsDelegate(variableSettings, psiClassType);
  } else {
    return variableSettings;
  }
}
 
Example #26
Source File: HaxeInheritPsiMixinImpl.java    From intellij-haxe with Apache License 2.0 5 votes vote down vote up
@NotNull
@Override
public PsiClassType[] getReferencedTypes() {
  LOG.debug("getReferencedTypes");
  PsiJavaCodeReferenceElement[] refs = getReferenceElements();
  PsiElementFactory factory = JavaPsiFacade.getInstance(getProject()).getElementFactory();
  PsiClassType[] types = new PsiClassType[refs.length];
  for (int i = 0; i < types.length; i++) {
    types[i] = factory.createType(refs[i]);
  }

  return types;
}
 
Example #27
Source File: DebugLintIssue.java    From Debug with Apache License 2.0 5 votes vote down vote up
private static boolean isSubclassOf(
        @NonNull JavaContext context,
        @NonNull UExpression expression,
        @NonNull Class<?> cls) {

    final PsiType expressionType = expression.getExpressionType();
    if (!(expressionType instanceof PsiClassType)) {
        return false;
    }

    final PsiClassType classType = (PsiClassType) expressionType;
    final PsiClass resolvedClass = classType.resolve();
    return context.getEvaluator().extendsClass(resolvedClass, cls.getName(), false);
}
 
Example #28
Source File: ThrowsVariableGenerator.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
@Override
public String generate(PsiElement element) {
    if (!(element instanceof PsiMethod)) {
        return "";
    }
    List<String> exceptionNameList = Arrays.stream(((PsiMethod)element).getThrowsList().getReferencedTypes())
        .map(PsiClassType::getName).collect(Collectors.toList());
    if (exceptionNameList.isEmpty()) {
        return "";
    }
    return exceptionNameList.stream()
        .map(name -> "@throws " + name + " " + translatorService.translate(name))
        .collect(Collectors.joining("\n"));
}
 
Example #29
Source File: BeanUtils.java    From camel-idea-plugin with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #30
Source File: JavaPsiUtil.java    From idea-android-studio-plugin with GNU General Public License v2.0 5 votes vote down vote up
public static boolean isInstanceOf(PsiClass instance, PsiClass interfaceExtendsClass) {

        String className = interfaceExtendsClass.getQualifiedName();
        if(className == null) {
            return true;
        }

        if(className.equals(instance.getQualifiedName())) {
            return true;
        }

        for(PsiClassType psiClassType: PsiClassImplUtil.getExtendsListTypes(instance)) {
            PsiClass resolve = psiClassType.resolve();
            if(resolve != null) {
                if(className.equals(resolve.getQualifiedName())) {
                    return true;
                }
            }
        }

        for(PsiClass psiInterface: PsiClassImplUtil.getInterfaces(instance)) {
            if(className.equals(psiInterface.getQualifiedName())) {
                return true;
            }
        }

        return false;
    }