下面列出了怎么用com.intellij.psi.PsiMember的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Location toLocation(PsiMember psiMember) {
PsiElement sourceElement = psiMember.getNavigationElement();
if (sourceElement != null) {
PsiFile file = sourceElement.getContainingFile();
Location location = new Location();
location.setUri(VfsUtilCore.convertToURL(file.getVirtualFile().getUrl()).toExternalForm());
Document document = PsiDocumentManager.getInstance(psiMember.getProject()).getDocument(file);
TextRange range = sourceElement.getTextRange();
int startLine = document.getLineNumber(range.getStartOffset());
int startLineOffset = document.getLineStartOffset(startLine);
int endLine = document.getLineNumber(range.getEndOffset());
int endLineOffset = document.getLineStartOffset(endLine);
location.setRange(new Range(LSPIJUtils.toPosition(range.getStartOffset(), document), LSPIJUtils.toPosition(range.getEndOffset(), document)));
return location;
}
return null;
}
private static String convertName(String name, PsiMember member, PsiAnnotation configPropertiesAnnotation,
ConfigPropertiesContext configPropertiesContext) {
if (!configPropertiesContext.isSupportNamingStrategy()) {
// Quarkus < 1.2, the property name is the same than the method, field name
return name;
}
// Quarkus >=1.2
// check if the ConfigProperties use the namingStrategy
String namingStrategy = getAnnotationMemberValue(configPropertiesAnnotation,
QuarkusConstants.CONFIG_PROPERTIES_ANNOTATION_NAMING_STRATEGY);
if (namingStrategy != null) {
switch (namingStrategy) {
case QuarkusConstants.CONFIG_PROPERTIES_NAMING_STRATEGY_ENUM_FROM_CONFIG:
return convertDefaultName(name, configPropertiesContext);
case QuarkusConstants.CONFIG_PROPERTIES_NAMING_STRATEGY_ENUM_VERBATIM:
return name;
case QuarkusConstants.CONFIG_PROPERTIES_NAMING_STRATEGY_ENUM_KEBAB_CASE:
return hyphenate(name);
}
}
// None namingStrategy, use default name
return convertDefaultName(name, configPropertiesContext);
}
@Override
protected void processAnnotation(PsiModifierListOwner javaElement, PsiAnnotation mpftAnnotation, String annotationName,
SearchContext context) {
if (!(javaElement instanceof PsiMember)) {
return;
}
// The java element is method or a class
MicroProfileFaultToleranceContext mpftContext = getMicroProfileFaultToleranceContext(context);
AnnotationInfo info = mpftContext.getAnnotationInfo(annotationName);
if (info != null) {
// 1. Collect properties for <annotation>/<list of parameters>
collectProperties(context.getCollector(), info, null, null, mpftContext);
mpftContext.addFaultToleranceProperties(context.getCollector());
// 2. Collect properties for <classname>/<annotation>/<list of parameters>
if (javaElement instanceof PsiMethod) {
PsiMethod annotatedMethod = (PsiMethod) javaElement;
PsiClass classType = annotatedMethod.getContainingClass();
PsiAnnotation mpftAnnotationForClass = getAnnotation(classType, annotationName);
collectProperties(context.getCollector(), info, classType, mpftAnnotationForClass, mpftContext);
}
// 3. Collect properties for <classname>/<annotation>/<list of parameters> or
// <classname>/<methodname>/<annotation>/<list of parameters>
collectProperties(context.getCollector(), info, (PsiMember) javaElement, mpftAnnotation, mpftContext);
}
}
public Location findPropertyLocation(Module module, String sourceType, String sourceField, String sourceMethod, IPsiUtils utils) {
return DumbService.getInstance(module.getProject()).runReadActionInSmartMode(() -> {
PsiMember fieldOrMethod = findDeclaredProperty(module, sourceType, sourceField, sourceMethod, utils);
if (fieldOrMethod != null) {
PsiFile classFile = fieldOrMethod.getContainingFile();
if (classFile != null) {
// Try to download source if required
if (utils != null) {
utils.discoverSource(classFile);
}
}
return utils.toLocation(fieldOrMethod);
}
return null;
});
}
@Nullable
public static String computeDocumentation(PsiMember member) {
PsiDocComment docComment;
if (member instanceof PsiField) {
docComment = PsiField.class.cast(member).getDocComment();
} else if (member instanceof PsiMethod) {
docComment = PsiMethod.class.cast(member).getDocComment();
} else {
throw new RuntimeException("Method supports targets of type PsiField & PsiMethod only");
}
if (docComment != null) {
StringBuilder builder = new StringBuilder();
new JavaDocInfoGenerator(member.getProject(), member)
.generateCommonSection(builder, docComment);
return builder.toString().trim();
}
return null;
}
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
final MemberSelectionPanel memberSelectionPanel = new MemberSelectionPanel(RefactoringBundle.message("members.to.form.superclass"),
myMemberInfos, RefactoringBundle.message("make.abstract"));
panel.add(memberSelectionPanel, BorderLayout.CENTER);
final MemberInfoModel<PsiMember, MemberInfo> memberInfoModel =
new UsesAndInterfacesDependencyMemberInfoModel<PsiMember, MemberInfo>(mySourceClass, null, false, myContainmentVerifier) {
@Override
public Boolean isFixedAbstract(MemberInfo member) {
return Boolean.TRUE;
}
};
memberInfoModel.memberInfoChanged(new MemberInfoChange<PsiMember, MemberInfo>(myMemberInfos));
memberSelectionPanel.getTable().setMemberInfoModel(memberInfoModel);
memberSelectionPanel.getTable().addMemberInfoChangeListener(memberInfoModel);
panel.add(myDocCommentPanel, BorderLayout.EAST);
return panel;
}
protected JComponent createCenterPanel() {
JPanel panel = new JPanel(new BorderLayout());
final MemberSelectionPanel memberSelectionPanel = new MemberSelectionPanel(
RefactoringBundle.message("members.to.be.pushed.down.panel.title"),
myMemberInfos,
RefactoringBundle.message("keep.abstract.column.header"));
panel.add(memberSelectionPanel, BorderLayout.CENTER);
myMemberInfoModel = new MyMemberInfoModel();
myMemberInfoModel.memberInfoChanged(new MemberInfoChange<PsiMember, MemberInfo>(myMemberInfos));
memberSelectionPanel.getTable().setMemberInfoModel(myMemberInfoModel);
memberSelectionPanel.getTable().addMemberInfoChangeListener(myMemberInfoModel);
myJavaDocPanel = new DocCommentPanel(RefactoringBundle.message("push.down.javadoc.panel.title"));
myJavaDocPanel.setPolicy(JavaRefactoringSettings.getInstance().PULL_UP_MEMBERS_JAVADOC);
panel.add(myJavaDocPanel, BorderLayout.EAST);
return panel;
}
static String getInnerClassName(PsiMember field) {
final StringBuilder builder = new StringBuilder();
PsiMember currElement = field;
while ((currElement = currElement.getContainingClass()) != null) {
builder.insert(0, currElement.getName() + ".");
}
final String res = builder.toString();
return res.substring(0, res.length() - 1);
}
Optional<? extends PsiMember> getUnitAt(int virtualRow, int column) {
final int row = virtualRows.get(virtualRow);
switch (column) {
case ENTITY_COLUMN_INDEX:
return refactorings.get(row).getOptionalMethod();
case MOVE_TO_COLUMN_INDEX:
return refactorings.get(row).getOptionalTargetClass();
}
throw new IndexOutOfBoundsException("Unexpected column index: " + column);
}
@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));
}
}
}
/** * Returns the Java field from the given property source
*
* @param module the Java project
* @param sourceType the source type (class or interface)
* @param sourceField the source field and null otherwise.
* @param sourceMethod the source method and null otherwise.
* @return the Java field from the given property sources
*/
public PsiMember findDeclaredProperty(Module module, String sourceType, String sourceField,
String sourceMethod, IPsiUtils utils) {
if (sourceType == null) {
return null;
}
// Try to find type with standard classpath
PsiClass type = utils.findClass(module, sourceType);
if (type == null) {
return null;
}
if (sourceField != null) {
return type.findFieldByName(sourceField, true);
}
if (sourceMethod != null) {
int startBracketIndex = sourceMethod.indexOf('(');
String methodName = sourceMethod.substring(0, startBracketIndex);
// Method signature has been generated with PSI API, so we are sure that we have
// a ')' character.
for(PsiMethod method : type.findMethodsByName(methodName, true)) {
String signature = PsiTypeUtils.getSourceMethod(method);
if (signature.equals(sourceMethod)) {
return method;
}
}
}
return type;
}
public static void updateConverterKinds(ItemMetadata metadata, PsiMember member, PsiClass enclosedType) {
if (enclosedType == null || !enclosedType.isEnum()) {
return;
}
// By default Quarkus set the enum values as kebab and verbatim
metadata.setConverterKinds(DEFAULT_QUARKUS_CONVERTERS);
}
/**
* Returns the annotation from the given <code>annotatable</code> element with
* the given name <code>annotationName</code> and null otherwise.
*
* @param annotatable the class, field which can be annotated.
* @param annotationName the annotation name
* @return the annotation from the given <code>annotatable</code> element with
* the given name <code>annotationName</code> and null otherwise.
*/
public static PsiAnnotation getAnnotation(PsiMember annotatable, String annotationName) {
if (annotatable == null) {
return null;
}
PsiAnnotation[] annotations = annotatable.getAnnotations();
for (PsiAnnotation annotation : annotations) {
if (isMatchAnnotation(annotation, annotationName)) {
return annotation;
}
}
return null;
}
public static String getSourceType(PsiModifierListOwner psiElement) {
if (psiElement instanceof PsiField || psiElement instanceof PsiMethod) {
return ClassUtil.getJVMClassName(((PsiMember)psiElement).getContainingClass());
} else if (psiElement instanceof PsiParameter) {
return ClassUtil.getJVMClassName(((PsiMethod)((PsiParameter)psiElement).getDeclarationScope()).getContainingClass());
}
return null;
}
private static Reader getHTMLContentReader(PsiMember member, boolean allowInherited, boolean useAttachedJavadoc) {
PsiDocComment doc = ((PsiDocCommentOwner) member).getDocComment();
PsiElement sourceMember = member.getNavigationElement();
if (sourceMember instanceof PsiDocCommentOwner) {
doc = ((PsiDocCommentOwner) sourceMember).getDocComment();
}
return doc == null ? null : new JavaDocCommentReader(doc.getText());
}
/**
* Gets a reader for an IMember's Javadoc comment content from the source
* attachment. and renders the tags in plain text. Returns <code>null</code> if
* the member does not contain a Javadoc comment or if no source is available.
*
* @param member
* the member to get the Javadoc of.
* @return a reader for the Javadoc comment content in plain text or
* <code>null</code> if the member does not contain a Javadoc comment or
* if no source is available
*/
public static Reader getPlainTextContentReader(PsiMember member) {
Reader contentReader = getHTMLContentReader(member, true, true);
if (contentReader != null) {
try {
return new JavaDoc2PlainTextConverter(contentReader).getAsReader();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return null;
}
public GenericClassMemberWrapper(@NotNull PsiMember member) {
this.member = member;
this.originalName = requireNonNull(member.getName());
this.documentation = computeDocumentation(member);
this.shortType = toClassNonQualifiedName(getReferredPsiType(member));
this.deprecated = computeDeprecationStatus();
}
public HaxeMemberModel getMemberModel() {
HaxeMemberModel model = getBasePsi().getUserData(PARAMETER_MEMBER_MODEL_KEY);
if (model == null) {
final PsiMember parentPsi = PsiTreeUtil.getParentOfType(getBasePsi(), HaxeEnumValueDeclaration.class, HaxeMethod.class);
if (parentPsi instanceof HaxeMethod) {
model = ((HaxeMethod)parentPsi).getModel();
} else if (parentPsi instanceof HaxeEnumValueDeclaration) {
model = new HaxeFieldModel((HaxePsiField)parentPsi);
}
if (model != null) {
getBasePsi().putUserData(PARAMETER_MEMBER_MODEL_KEY, model);
}
}
return model;
}
@Override
public boolean canBeFinal(PsiMember member) {
if (member instanceof PsiField) {
if (PsiAnnotationSearchUtil.isAnnotatedWith(member, Setter.class)) {
return false;
}
final PsiClass psiClass = PsiTreeUtil.getParentOfType(member, PsiClass.class);
return null == psiClass || !PsiAnnotationSearchUtil.isAnnotatedWith(psiClass, Setter.class, Data.class, Value.class);
}
return true;
}
@NotNull
Collection<LombokProcessorData> getApplicableProcessors(@NotNull PsiMember psiMember) {
Collection<LombokProcessorData> result = Collections.emptyList();
if (verifyLombokAnnotationPresent(psiMember)) {
result = new ArrayList<>();
addApplicableProcessors(psiMember, result);
final PsiClass psiClass = psiMember.getContainingClass();
if (null != psiClass) {
addApplicableProcessors(psiClass, result);
}
}
return result;
}
private boolean verifyLombokAnnotationPresent(@NotNull PsiMember psiMember) {
if (PsiAnnotationSearchUtil.checkAnnotationsSimpleNameExistsIn(psiMember, registeredAnnotationNames)) {
return true;
}
final PsiClass psiClass = psiMember.getContainingClass();
return null != psiClass && verifyLombokAnnotationPresent(psiClass);
}
private void addApplicableProcessors(@NotNull PsiMember psiMember, @NotNull Collection<LombokProcessorData> target) {
final PsiModifierList psiModifierList = psiMember.getModifierList();
if (null != psiModifierList) {
for (PsiAnnotation psiAnnotation : psiModifierList.getAnnotations()) {
for (Processor processor : getProcessors(psiAnnotation)) {
target.add(new LombokProcessorData(processor, psiAnnotation));
}
}
}
}
private void collectProperties(IPropertiesCollector collector, AnnotationInfo info, PsiMember annotatedClassOrMethod,
PsiAnnotation mpftAnnotation, MicroProfileFaultToleranceContext mpftContext) {
String annotationName = info.getSimpleName();
String className = null;
String methodName = null;
boolean binary = false;
String sourceType = null;
String sourceMethod = null;
if (annotatedClassOrMethod != null) {
binary = PsiTypeUtils.isBinary(annotatedClassOrMethod);
if (annotatedClassOrMethod instanceof PsiClass) {
PsiClass annotatedClass = (PsiClass) annotatedClassOrMethod;
className = annotatedClass.getQualifiedName();
// Check if properties has been generated for the <classname><annotation>:
if (isProcessed(className, annotationName, mpftContext)) {
return;
}
sourceType = getPropertyType(annotatedClass, className);
} else if (annotatedClassOrMethod instanceof PsiMethod) {
PsiMethod annotatedMethod = (PsiMethod) annotatedClassOrMethod;
className = annotatedMethod.getContainingClass().getQualifiedName();
methodName = annotatedMethod.getName();
sourceType = getSourceType(annotatedMethod);
sourceMethod = getSourceMethod(annotatedMethod);
}
} else {
// Check if properties has been generated for the <annotation>:
if (isProcessed(null, annotationName, mpftContext)) {
return;
}
}
String prefix = createPrefix(className, methodName, annotationName);
// parameter
List<AnnotationParameter> parameters = info.getParameters();
for (AnnotationParameter parameter : parameters) {
String propertyName = new StringBuilder(prefix).append('/').append(parameter.getName()).toString();
String parameterType = parameter.getType();
String description = parameter.getDescription();
String defaultValue = getParameterDefaultValue(parameter, mpftAnnotation);
String extensionName = null;
if (annotatedClassOrMethod == null) {
sourceType = parameter.getSourceType();
sourceMethod = parameter.getSourceMethod();
}
// Enumerations
PsiClass jdtType = parameter.getJDTType();
super.updateHint(collector, jdtType);
super.addItemMetadata(collector, propertyName, parameterType, description, sourceType, null, sourceMethod,
defaultValue, extensionName, binary);
}
}
public static boolean hasAnnotation(PsiMember annotatable, String annotationName) {
return getAnnotation(annotatable, annotationName) != null;
}
public static String getSourceField(PsiMember psiMember) {
return psiMember.getName();
}
@NotNull
@Override
protected List<? extends GenerationInfo> generateMemberPrototypes(
PsiClass aClass, ClassMember[] members) throws IncorrectOperationException {
return Collections.singletonList(new PsiGenerationInfo<PsiMember>(generatedMethod));
}
@Nullable
private static PsiType eraseFreeTypeParameters(@Nullable PsiType psiType,
@NotNull PsiMember member) {
final PsiClass containingClass = member.getContainingClass();
return eraseFreeTypeParameters(psiType, containingClass);
}
public HaxeMemberModel(PsiMember basePsi) {
super(basePsi);
}
public PsiMember getMemberPsi() {
return (PsiMember)basePsi;
}
@Override
protected String buildFunctionsText(HaxeNamedComponent element) {
final HaxeComponentType componentType = HaxeComponentType.typeOf(element);
final StringBuilder result = new StringBuilder();
final PsiClass containingClass = element instanceof PsiMember ? ((PsiMember)element).getContainingClass() : null;
final boolean isInterfaceElement = containingClass != null && containingClass.isInterface();
boolean addOverride = !isInterfaceElement && override && !element.isOverride();
if (addOverride) {
result.append("override ");
}
final HaxePsiModifier[] declarationAttributeList = PsiTreeUtil.getChildrenOfType(element, HaxePsiModifier.class);
if (declarationAttributeList != null) {
result.append(StringUtil.join(declarationAttributeList, new Function<HaxePsiModifier, String>() {
@Override
public String fun(HaxePsiModifier attribute) {
return attribute.getText();
}
}, " "));
result.append(" ");
}
if (isInterfaceElement && !result.toString().contains("public")) {
result.insert(0, "public ");
}
if (componentType == HaxeComponentType.FIELD) {
result.append("var ");
result.append(element.getName());
} else {
result.append("function ");
appendMethodNameAndParameters(result, element, true);
}
final HaxeTypeTag typeTag = PsiTreeUtil.getChildOfType(element, HaxeTypeTag.class);
String type = null;
if (typeTag != null && typeTag.getTypeOrAnonymous() != null) {
result.append(":");
type = HaxePresentableUtil.buildTypeText(element, typeTag.getTypeOrAnonymous().getType(), specializations);
result.append(type);
}
if(componentType == HaxeComponentType.FIELD) {
result.append(";");
} else {
result.append("{\n");
if(addOverride || element.isOverride()) {
if(type != null && !type.equals("Void")) {
result.append("return ");
}
result.append("super.");
appendMethodNameAndParameters(result, element, false);
result.append(";\n");
}
result.append("}");
}
return result.toString();
}