下面列出了怎么用com.intellij.psi.PsiMethod的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
@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);
}
}
@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;
}
@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);
}
}
}
};
}
@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
}
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;
}
@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();
}
}
}
}
@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;
}
}
@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);
}
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;
}
/**
* 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;
}
/**
* 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;
}
/**
* 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());
}
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);
}
@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);
}
@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);
}
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);
}
}
}
@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;
}
/** 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);
}
@Override
public String generate(PsiElement psiElement) {
if (!(psiElement instanceof PsiMethod)) {
return StringUtils.EMPTY;
}
PsiMethod psiMethod = (PsiMethod) psiElement;
if (config != null && config.getMethodTemplateConfig() != null
&& Boolean.TRUE.equals(config.getMethodTemplateConfig().getIsDefault())) {
return defaultGenerate(psiMethod);
} else {
return customGenerate(psiMethod);
}
}
protected void processClass(@NotNull PsiClass psiClass) {
final Map<PsiField, PsiMethod> fieldMethodMap = new HashMap<>();
for (PsiField psiField : psiClass.getFields()) {
PsiMethod propertyGetter = PropertyUtil.findPropertyGetter(psiClass, psiField.getName(), psiField.hasModifierProperty(PsiModifier.STATIC), false);
if (null != propertyGetter) {
fieldMethodMap.put(psiField, propertyGetter);
}
}
processIntern(fieldMethodMap, psiClass, Getter.class);
}
@Override
public String generate(PsiElement element) {
if (!(element instanceof PsiMethod)) {
return "";
}
List<String> paramNameList = Arrays.stream(((PsiMethod)element).getParameterList().getParameters())
.map(PsiParameter::getName).collect(Collectors.toList());
if (paramNameList.isEmpty()) {
return "";
}
return paramNameList.stream()
.map(param -> "@param " + param + " " + translatorService.translate(param))
.collect(Collectors.joining("\n"));
}
@Override
public String generate(PsiElement element) {
if (element instanceof PsiClass) {
PsiClass superClass = ((PsiClass) element).getSuperClass();
PsiClass[] interfaces = ((PsiClass) element).getInterfaces();
List<String> superList = Lists.newArrayList();
if (superClass != null) {
if (!"Object".equalsIgnoreCase(superClass.getName())) {
superList.add(superClass.getName());
}
}
if (interfaces.length > 0) {
superList.addAll(Arrays.stream(interfaces).map(PsiClass::getName).collect(Collectors.toList()));
}
return superList.stream().map(sup -> "@see " + sup).collect(Collectors.joining("\n"));
} else if (element instanceof PsiMethod) {
return "";
} else if (element instanceof PsiField) {
String type = ((PsiField)element).getType().getPresentableText();
if (Consts.BASE_TYPE_SET.contains(type)) {
return "";
}
return "@see " + type;
} else {
return "";
}
}
@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"));
}
@Test
public void findFirstParent() {
testHelper.getPsiClass(
psiClasses -> {
Assert.assertNotNull(psiClasses);
Assert.assertEquals(2, psiClasses.size());
PsiMethod layoutSpecMethod = psiClasses.get(0).getMethods()[0];
Optional<PsiClass> layoutSpec =
CompletionUtils.findFirstParent(layoutSpecMethod, LithoPluginUtils::isLayoutSpec);
Assert.assertTrue(layoutSpec.isPresent());
Optional<PsiClass> componentCls =
CompletionUtils.findFirstParent(layoutSpecMethod, LithoPluginUtils::isComponentClass);
Assert.assertFalse(componentCls.isPresent());
PsiMethod sectionSpecMethod = psiClasses.get(1).getMethods()[0];
Optional<PsiClass> layoutSpecInSection =
CompletionUtils.findFirstParent(sectionSpecMethod, LithoPluginUtils::isLayoutSpec);
Assert.assertFalse(layoutSpecInSection.isPresent());
Optional<PsiClass> lithoSpec =
CompletionUtils.findFirstParent(sectionSpecMethod, LithoPluginUtils::isLithoSpec);
Assert.assertTrue(lithoSpec.isPresent());
return true;
},
"LayoutSpec.java",
"SectionSpec.java");
}
public static MethodFQN create(PsiMethod psiMethod) {
String classFqn = ClassFQN.create(psiMethod.getContainingClass()).getFQN();
String methodName = psiMethod.getName();
Builder builder = new Builder(classFqn, methodName);
List<String> parameters = getParameterArray(psiMethod);
for (String parameter : parameters) {
builder.addParameter(parameter);
}
return builder.create();
}
private static PsiMethod getTestMethod(ConfigurationContext context) {
PsiElement psi = context.getPsiLocation();
if (psi instanceof PsiMethod
&& AnnotationUtil.isAnnotated((PsiMethod) psi, JUnitUtil.TEST_ANNOTATION, false)) {
return (PsiMethod) psi;
}
List<PsiMethod> selectedMethods = TestMethodSelectionUtil.getSelectedMethods(context);
return selectedMethods != null && selectedMethods.size() == 1 ? selectedMethods.get(0) : null;
}
private static boolean isJUnit3TestMethod(PsiMethod psiMethod) {
return psiMethod.hasModifier(JvmModifier.PUBLIC)
&& !psiMethod.hasModifier(JvmModifier.STATIC)
&& !psiMethod.hasModifier(JvmModifier.ABSTRACT)
&& PsiType.VOID.equals(psiMethod.getReturnType())
&& psiMethod.getName().startsWith("test")
&& psiMethod.getParameterList().isEmpty();
}
private void runFindUsageReadAction(final PsiElement psiElement, final Processor<? super UsageInfo> processor, final FindUsagesOptions findUsagesOptions) {
ApplicationManager.getApplication().runReadAction(() -> {
if (psiElement instanceof PsiMethod) {
PsiMethod[] psiMethods = SuperMethodWarningUtil.checkSuperMethods((PsiMethod) psiElement, CustomFUH.getActionString());
if (psiMethods.length < 1) return;
for (PsiElement method : psiMethods)
StepFindUsagesHandler.this.processUsages(method, processor, findUsagesOptions);
}
StepFindUsagesHandler.this.processUsages(psiElement, processor, findUsagesOptions);
});
}
private static boolean canHaveSuperMethod(PsiMethod method, boolean allowStaticMethod) {
// Private really means protected in Haxe, so this version skips the private test.
if (null == method || method.isConstructor()) return false;
if (!allowStaticMethod && method.hasModifierProperty(PsiModifier.STATIC)) return false;
PsiClass parentClass = method.getContainingClass();
return parentClass != null;
}