下面列出了怎么用org.eclipse.jdt.core.dom.IMethodBinding的API类实例代码及写法,或者点击链接到github查看源代码。
private static void addParameterMissmatchProposals(IInvocationContext context, IProblemLocationCore problem,
List<IMethodBinding> similarElements, ASTNode invocationNode, List<Expression> arguments,
Collection<ChangeCorrectionProposal> proposals) throws CoreException {
int nSimilarElements= similarElements.size();
ITypeBinding[] argTypes= getArgumentTypes(arguments);
if (argTypes == null || nSimilarElements == 0) {
return;
}
for (int i= 0; i < nSimilarElements; i++) {
IMethodBinding elem = similarElements.get(i);
int diff= elem.getParameterTypes().length - argTypes.length;
if (diff == 0) {
int nProposals= proposals.size();
doEqualNumberOfParameters(context, invocationNode, problem, arguments, argTypes, elem, proposals);
if (nProposals != proposals.size()) {
return; // only suggest for one method (avoid duplicated proposals)
}
} else if (diff > 0) {
doMoreParameters(context, invocationNode, argTypes, elem, proposals);
} else {
doMoreArguments(context, invocationNode, arguments, argTypes, elem, proposals);
}
}
}
private static void createTypeParameters(ImportRewrite imports, ImportRewriteContext context, AST ast, IMethodBinding binding, MethodDeclaration decl) {
ITypeBinding[] typeParams= binding.getTypeParameters();
List<TypeParameter> typeParameters= decl.typeParameters();
for (int i= 0; i < typeParams.length; i++) {
ITypeBinding curr= typeParams[i];
TypeParameter newTypeParam= ast.newTypeParameter();
newTypeParam.setName(ast.newSimpleName(curr.getName()));
ITypeBinding[] typeBounds= curr.getTypeBounds();
if (typeBounds.length != 1 || !"java.lang.Object".equals(typeBounds[0].getQualifiedName())) {//$NON-NLS-1$
List<Type> newTypeBounds= newTypeParam.typeBounds();
for (int k= 0; k < typeBounds.length; k++) {
newTypeBounds.add(imports.addImport(typeBounds[k], ast, context));
}
}
typeParameters.add(newTypeParam);
}
}
private static boolean isMoveStaticMemberAvailable(ASTNode declaration) throws JavaModelException {
if (declaration instanceof MethodDeclaration) {
IMethodBinding method = ((MethodDeclaration) declaration).resolveBinding();
return method != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IMember) method.getJavaElement());
} else if (declaration instanceof FieldDeclaration) {
List<IMember> members = new ArrayList<>();
for (Object fragment : ((FieldDeclaration) declaration).fragments()) {
IVariableBinding variable = ((VariableDeclarationFragment) fragment).resolveBinding();
if (variable != null) {
members.add((IField) variable.getJavaElement());
}
}
return RefactoringAvailabilityTesterCore.isMoveStaticMembersAvailable(members.toArray(new IMember[0]));
} else if (declaration instanceof AbstractTypeDeclaration) {
ITypeBinding type = ((AbstractTypeDeclaration) declaration).resolveBinding();
return type != null && RefactoringAvailabilityTesterCore.isMoveStaticAvailable((IType) type.getJavaElement());
}
return false;
}
/**
* {@inheritDoc}
*/
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
CompilationUnit compilationUnit= cuRewrite.getRoot();
importType(fDeclaringClass, fName, cuRewrite.getImportRewrite(), compilationUnit);
TextEditGroup group;
if (fName.resolveBinding() instanceof IMethodBinding) {
group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyMethodWithDeclClass_description, cuRewrite);
} else {
group= createTextEditGroup(FixMessages.CodeStyleFix_QualifyFieldWithDeclClass_description, cuRewrite);
}
IJavaElement javaElement= fDeclaringClass.getJavaElement();
if (javaElement instanceof IType) {
Name qualifierName= compilationUnit.getAST().newName(((IType)javaElement).getElementName());
SimpleName simpleName= (SimpleName)rewrite.createMoveTarget(fName);
QualifiedName qualifiedName= compilationUnit.getAST().newQualifiedName(qualifierName, simpleName);
rewrite.replace(fName, qualifiedName, group);
}
}
public static boolean equalSignature(IMethodBinding methodBinding1, IMethodBinding methodBinding2) {
if(!methodBinding1.getName().equals(methodBinding2.getName()))
return false;
ITypeBinding returnType1 = methodBinding1.getReturnType();
ITypeBinding returnType2 = methodBinding2.getReturnType();
if(!equalType(returnType1, returnType2))
return false;
ITypeBinding[] parameterTypes1 = methodBinding1.getParameterTypes();
ITypeBinding[] parameterTypes2 = methodBinding2.getParameterTypes();
if(parameterTypes1.length == parameterTypes2.length) {
int i = 0;
for(ITypeBinding typeBinding1 : parameterTypes1) {
ITypeBinding typeBinding2 = parameterTypes2[i];
if(!equalType(typeBinding1, typeBinding2))
return false;
i++;
}
}
else return false;
return true;
}
/**
* Creates a new add custom constructor operation.
*
* @param astRoot the compilation unit ast node
* @param parentType the type to add the methods to
* @param variables the variable bindings to use in the constructor
* @param constructor the method binding of the super constructor
* @param insert the insertion point, or <code>null</code>
* @param settings the code generation settings to use
* @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
* @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
*/
public AddCustomConstructorOperation(CompilationUnit astRoot, ITypeBinding parentType, IVariableBinding[] variables, IMethodBinding constructor, IJavaElement insert, CodeGenerationSettings settings, boolean apply, boolean save) {
Assert.isTrue(astRoot != null && astRoot.getTypeRoot() instanceof ICompilationUnit);
Assert.isNotNull(parentType);
Assert.isNotNull(variables);
Assert.isNotNull(constructor);
Assert.isNotNull(settings);
fParentType= parentType;
fInsert= insert;
fASTRoot= astRoot;
fFieldBindings= variables;
fConstructorBinding= constructor;
fSettings= settings;
fSave= save;
fApply= apply;
}
private static String asString(IMethodBinding method) {
StringBuffer result= new StringBuffer();
result.append(method.getDeclaringClass().getName());
result.append(':');
result.append(method.getName());
result.append('(');
ITypeBinding[] parameters= method.getParameterTypes();
int lastComma= parameters.length - 1;
for (int i= 0; i < parameters.length; i++) {
ITypeBinding parameter= parameters[i];
result.append(parameter.getName());
if (i < lastComma)
result.append(", "); //$NON-NLS-1$
}
result.append(')');
return result.toString();
}
private static CompilationUnit findCUForMethod(CompilationUnit compilationUnit, ICompilationUnit cu, IMethodBinding methodBinding) {
ASTNode methodDecl= compilationUnit.findDeclaringNode(methodBinding.getMethodDeclaration());
if (methodDecl == null) {
// is methodDecl defined in another CU?
ITypeBinding declaringTypeDecl= methodBinding.getDeclaringClass().getTypeDeclaration();
if (declaringTypeDecl.isFromSource()) {
ICompilationUnit targetCU= null;
try {
targetCU= ASTResolving.findCompilationUnitForBinding(cu, compilationUnit, declaringTypeDecl);
} catch (JavaModelException e) { /* can't do better */
}
if (targetCU != null) {
return ASTResolving.createQuickFixAST(targetCU, null);
}
}
return null;
}
return compilationUnit;
}
private Set<IMethodBinding> getDeclaredMethods(ITypeBinding typeBinding) {
Set<IMethodBinding> declaredMethods = new LinkedHashSet<IMethodBinding>();
//first add the directly declared methods
for(IMethodBinding methodBinding : typeBinding.getDeclaredMethods()) {
declaredMethods.add(methodBinding);
}
ITypeBinding superclassTypeBinding = typeBinding.getSuperclass();
if(superclassTypeBinding != null) {
declaredMethods.addAll(getDeclaredMethods(superclassTypeBinding));
}
ITypeBinding[] interfaces = typeBinding.getInterfaces();
for(ITypeBinding interfaceTypeBinding : interfaces) {
declaredMethods.addAll(getDeclaredMethods(interfaceTypeBinding));
}
return declaredMethods;
}
private Expression convert(org.eclipse.jdt.core.dom.MethodInvocation methodInvocation) {
Expression qualifier = getExplicitQualifier(methodInvocation);
IMethodBinding methodBinding = methodInvocation.resolveMethodBinding();
MethodDescriptor methodDescriptor = JdtUtils.createMethodDescriptor(methodBinding);
List<Expression> arguments =
convertArguments(methodBinding, JdtUtils.asTypedList(methodInvocation.arguments()));
MethodCall methodCall =
MethodCall.Builder.from(methodDescriptor)
.setQualifier(qualifier)
.setArguments(arguments)
.setSourcePosition(getSourcePosition(methodInvocation))
.build();
if (JdtUtils.hasUncheckedCastAnnotation(methodBinding)) {
// Annotate the invocation with the expected type. When InsertErasureSureTypeSafetyCasts
// runs, this invocation will be skipped as it will no longer be an assignment context.
return JsDocCastExpression.newBuilder()
.setExpression(methodCall)
.setCastType(methodDescriptor.getReturnTypeDescriptor())
.build();
}
return methodCall;
}
private ExpressionStatement convert(
org.eclipse.jdt.core.dom.SuperConstructorInvocation expression) {
IMethodBinding superConstructorBinding = expression.resolveConstructorBinding();
MethodDescriptor methodDescriptor = JdtUtils.createMethodDescriptor(superConstructorBinding);
List<Expression> arguments =
convertArguments(superConstructorBinding, JdtUtils.asTypedList(expression.arguments()));
Expression qualifier = convertOrNull(expression.getExpression());
// super() call to an inner class without explicit qualifier, find the enclosing instance.
DeclaredTypeDescriptor targetTypeDescriptor = methodDescriptor.getEnclosingTypeDescriptor();
if (qualifier == null
&& targetTypeDescriptor.getTypeDeclaration().isCapturingEnclosingInstance()) {
qualifier =
resolveImplicitOuterClassReference(targetTypeDescriptor.getEnclosingTypeDescriptor());
}
return MethodCall.Builder.from(methodDescriptor)
.setQualifier(qualifier)
.setArguments(arguments)
.setSourcePosition(getSourcePosition(expression))
.build()
.makeStatement(getSourcePosition(expression));
}
public void initByIMethodBinding(IMethodBinding mBinding) {
IMethod iMethod = (IMethod) mBinding.getJavaElement();
try {
key = iMethod.getKey().substring(0, iMethod.getKey().indexOf("("))
+ iMethod.getSignature();
projectName = mBinding.getJavaElement().getJavaProject()
.getElementName();
} catch (Exception e) {
projectName = "";
}
packageName = mBinding.getDeclaringClass().getPackage().getName();
className = mBinding.getDeclaringClass().getName();
name = mBinding.getName();
parameters = new ArrayList<>();
ITypeBinding[] parameterBindings = mBinding.getParameterTypes();
for (int i = 0; i < parameterBindings.length; i++) {
parameters.add(parameterBindings[i].getName());
}
}
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setIgnoreMethodBodies(true);
IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
parser.setProject(javaProject);
IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
ITypeBinding typeBinding = (ITypeBinding) bindings[0];
IMethodBinding[] methods = typeBinding.getDeclaredMethods();
for(IMethodBinding method: methods) {
if (method.isConstructor()) {
IMethod element = (IMethod) method.getJavaElement();
if (element.exists()) {
String[] parameterNames = element.getParameterNames();
if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
return true;
}
} else {
return false;
}
}
}
return false;
}
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
// TODO: update for fSelectionStart == -1
final Map<String, String> arguments= new HashMap<String, String>();
String project= null;
IJavaProject javaProject= fSelectionTypeRoot.getJavaProject();
if (javaProject != null)
project= javaProject.getElementName();
final IMethodBinding binding= fSourceProvider.getDeclaration().resolveBinding();
int flags= RefactoringDescriptor.STRUCTURAL_CHANGE | JavaRefactoringDescriptor.JAR_REFACTORING | JavaRefactoringDescriptor.JAR_SOURCE_ATTACHMENT;
if (!Modifier.isPrivate(binding.getModifiers()))
flags|= RefactoringDescriptor.MULTI_CHANGE;
final String description= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description_short, BasicElementLabels.getJavaElementName(binding.getName()));
final String header= Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_descriptor_description, new String[] { BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED), BindingLabelProvider.getBindingLabel(binding.getDeclaringClass(), JavaElementLabels.ALL_FULLY_QUALIFIED)});
final JDTRefactoringDescriptorComment comment= new JDTRefactoringDescriptorComment(project, this, header);
comment.addSetting(Messages.format(RefactoringCoreMessages.ReplaceInvocationsRefactoring_original_pattern, BindingLabelProvider.getBindingLabel(binding, JavaElementLabels.ALL_FULLY_QUALIFIED)));
if (!fTargetProvider.isSingle())
comment.addSetting(RefactoringCoreMessages.ReplaceInvocationsRefactoring_replace_references);
final JavaRefactoringDescriptor descriptor= new JavaRefactoringDescriptor(ID_REPLACE_INVOCATIONS, project, description, comment.asString(), arguments, flags){}; //REVIEW Unregistered ID!
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_INPUT, JavaRefactoringDescriptorUtil.elementToHandle(project, fSelectionTypeRoot));
arguments.put(JavaRefactoringDescriptorUtil.ATTRIBUTE_SELECTION, new Integer(fSelectionStart).toString() + " " + new Integer(fSelectionLength).toString()); //$NON-NLS-1$
arguments.put(ATTRIBUTE_MODE, new Integer(fTargetProvider.isSingle() ? 0 : 1).toString());
return new DynamicValidationRefactoringChange(descriptor, RefactoringCoreMessages.ReplaceInvocationsRefactoring_change_name, fChangeManager.getAllChanges());
}
public static TypeDeclaration findDeclaringTypeDeclaration(IMethodBinding methodBinding, TypeDeclaration typeDeclaration) {
if(typeDeclaration.resolveBinding().isEqualTo(methodBinding.getDeclaringClass())) {
return typeDeclaration;
}
//method was not found in typeDeclaration
Type superclassType = typeDeclaration.getSuperclassType();
if(superclassType != null) {
String superclassQualifiedName = superclassType.resolveBinding().getQualifiedName();
SystemObject system = ASTReader.getSystemObject();
ClassObject superclassObject = system.getClassObject(superclassQualifiedName);
if(superclassObject != null) {
AbstractTypeDeclaration superclassTypeDeclaration = superclassObject.getAbstractTypeDeclaration();
if(superclassTypeDeclaration instanceof TypeDeclaration) {
return findDeclaringTypeDeclaration(methodBinding, (TypeDeclaration)superclassTypeDeclaration);
}
}
}
return null;
}
private void setParameterNamesAndAnnotations(IMethodBinding method, ITypeBinding[] parameterTypes,
String[] parameterNames, JvmExecutable result) {
InternalEList<JvmFormalParameter> parameters = (InternalEList<JvmFormalParameter>)result.getParameters();
for (int i = 0; i < parameterTypes.length; i++) {
IAnnotationBinding[] parameterAnnotations;
try {
parameterAnnotations = method.getParameterAnnotations(i);
} catch(AbortCompilation aborted) {
parameterAnnotations = null;
}
ITypeBinding parameterType = parameterTypes[i];
String parameterName = parameterNames == null ? null /* lazy */ : i < parameterNames.length ? parameterNames[i] : "arg" + i;
JvmFormalParameter formalParameter = createFormalParameter(parameterType, parameterName, parameterAnnotations);
parameters.addUnique(formalParameter);
}
}
/**
* Creates a new add unimplemented constructors operation.
*
* @param astRoot the compilation unit AST node
* @param type the type to add the methods to
* @param constructorsToImplement the method binding keys to implement
* @param insertPos the insertion point, or <code>-1</code>
* @param imports <code>true</code> if the import edits should be applied, <code>false</code> otherwise
* @param apply <code>true</code> if the resulting edit should be applied, <code>false</code> otherwise
* @param save <code>true</code> if the changed compilation unit should be saved, <code>false</code> otherwise
*/
public AddUnimplementedConstructorsOperation(CompilationUnit astRoot, ITypeBinding type, IMethodBinding[] constructorsToImplement, int insertPos, final boolean imports, final boolean apply, final boolean save) {
if (astRoot == null || !(astRoot.getJavaElement() instanceof ICompilationUnit)) {
throw new IllegalArgumentException("AST must not be null and has to be created from a ICompilationUnit"); //$NON-NLS-1$
}
if (type == null) {
throw new IllegalArgumentException("The type must not be null"); //$NON-NLS-1$
}
ASTNode node= astRoot.findDeclaringNode(type);
if (!(node instanceof AnonymousClassDeclaration || node instanceof AbstractTypeDeclaration)) {
throw new IllegalArgumentException("type has to map to a type declaration in the AST"); //$NON-NLS-1$
}
fType= type;
fInsertPos= insertPos;
fASTRoot= astRoot;
fConstructorsToImplement= constructorsToImplement;
fSave= save;
fApply= apply;
fImports= imports;
fCreateComments= StubUtility.doAddComments(astRoot.getJavaElement().getJavaProject());
fVisibility= Modifier.PUBLIC;
fOmitSuper= false;
}
/**
* Creates a new return type variable.
*
* @param method the method binding
* @return the created return type variable, or <code>null</code>
*/
public final ConstraintVariable2 createReturnTypeVariable(final IMethodBinding method) {
if (!method.isConstructor()) {
ITypeBinding binding= method.getReturnType();
if (binding != null && binding.isArray())
binding= binding.getElementType();
if (binding != null && isConstrainedType(binding)) {
ConstraintVariable2 variable= null;
final TType type= createTType(binding);
if (method.getDeclaringClass().isFromSource())
variable= new ReturnTypeVariable2(type, method);
else
variable= new ImmutableTypeVariable2(type);
return fConstraintVariables.addExisting(variable);
}
}
return null;
}
private void handleResourceDeclarations(TryStatement tryStatement) {
List<VariableDeclarationExpression> resources= tryStatement.resources();
for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
iterator.next().accept(this);
}
//check if the exception is thrown as a result of resource#close()
boolean exitMarked= false;
for (VariableDeclarationExpression variable : resources) {
Type type= variable.getType();
IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
if (methodBinding != null) {
ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
for (int j= 0; j < exceptionTypes.length; j++) {
if (matches(exceptionTypes[j])) { // a close() throws the caught exception
// mark name of resource
for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
SimpleName name= fragment.getName();
fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
}
if (!exitMarked) {
// mark exit position
exitMarked= true;
Block body= tryStatement.getBody();
int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
BasicElementLabels.getJavaElementName(fException.getName()))));
}
}
}
}
}
}
private boolean handleExceptions(IMethodBinding binding, ASTNode node) {
if (binding == null) {
return true;
}
ITypeBinding[] exceptions = binding.getExceptionTypes();
for (int i = 0; i < exceptions.length; i++) {
addException(exceptions[i], node.getAST());
}
return true;
}
public ChangeMethodSignatureProposal(String label, ICompilationUnit targetCU, ASTNode invocationNode,
IMethodBinding binding, ChangeDescription[] paramChanges, ChangeDescription[] exceptionChanges,
int relevance) {
super(label, CodeActionKind.QuickFix, targetCU, null, relevance);
Assert.isTrue(binding != null && Bindings.isDeclarationBinding(binding));
fInvocationNode= invocationNode;
fSenderBinding= binding;
fParameterChanges= paramChanges;
fExceptionChanges= exceptionChanges;
}
private static String[] getMethodParameterTypes(IMethodBinding binding, boolean qualifiedName) {
List<String> parameterTypes = new ArrayList<>();
for (ITypeBinding type : binding.getParameterTypes()) {
if (qualifiedName) {
parameterTypes.add(type.getQualifiedName());
} else {
parameterTypes.add(type.getName());
}
}
return parameterTypes.toArray(new String[0]);
}
private static IMethodBinding findGetter(ProposalParameter context) {
ITypeBinding returnType= context.variableBinding.getType();
String getterName= GetterSetterUtil.getGetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean(context));
ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
if (declaringType == null)
return null;
IMethodBinding getter= Bindings.findMethodInHierarchy(declaringType, getterName, new ITypeBinding[0]);
if (getter != null && getter.getReturnType().isAssignmentCompatible(returnType) && Modifier.isStatic(getter.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))
return getter;
return null;
}
private static void addExplicitTypeArgumentsIfNecessary(ASTRewrite rewrite, ASTRewriteCorrectionProposal proposal, Expression invocation) {
if (Invocations.isResolvedTypeInferredFromExpectedType(invocation)) {
ITypeBinding[] typeArguments= Invocations.getInferredTypeArguments(invocation);
if (typeArguments == null)
return;
ImportRewrite importRewrite= proposal.getImportRewrite();
if (importRewrite == null) {
importRewrite= proposal.createImportRewrite((CompilationUnit) invocation.getRoot());
}
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(invocation, importRewrite);
AST ast= invocation.getAST();
ListRewrite typeArgsRewrite= Invocations.getInferredTypeArgumentsRewrite(rewrite, invocation);
for (int i= 0; i < typeArguments.length; i++) {
Type typeArgumentNode= importRewrite.addImport(typeArguments[i], ast, importRewriteContext);
typeArgsRewrite.insertLast(typeArgumentNode, null);
}
if (invocation instanceof MethodInvocation) {
MethodInvocation methodInvocation= (MethodInvocation) invocation;
Expression expression= methodInvocation.getExpression();
if (expression == null) {
IMethodBinding methodBinding= methodInvocation.resolveMethodBinding();
if (methodBinding != null && Modifier.isStatic(methodBinding.getModifiers())) {
expression= ast.newName(importRewrite.addImport(methodBinding.getDeclaringClass().getTypeDeclaration(), importRewriteContext));
} else {
expression= ast.newThisExpression();
}
rewrite.set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
}
}
}
}
/**
* NOTE: This method comes from StubUtility2.
*/
@SuppressWarnings("deprecation")
private static IMethodBinding findOverridingMethod(IMethodBinding method,
List<IMethodBinding> allMethods) {
for (IMethodBinding cur : allMethods) {
if (Bindings.areOverriddenMethods(cur, method)
|| Bindings.isSubsignature(cur, method)) {
return cur;
}
}
return null;
}
private static IMethodBinding resolveWellKnownCloneMethod(AST ast) {
IMethodBinding[] objectMethods = ast.resolveWellKnownType("java.lang.Object").getDeclaredMethods();
for (IMethodBinding method : objectMethods) {
if (method.getName().equals("clone") && method.getParameterTypes().length == 0) {
return method;
}
}
return null;
}
public static CheckDelegateMethodsResponse checkDelegateMethodsStatus(CodeActionParams params) {
IType type = SourceAssistProcessor.getSelectionType(params);
if (type == null || type.getCompilationUnit() == null) {
return new CheckDelegateMethodsResponse();
}
try {
RefactoringASTParser astParser = new RefactoringASTParser(IASTSharedValues.SHARED_AST_LEVEL);
CompilationUnit astRoot = astParser.parse(type.getCompilationUnit(), true);
ITypeBinding typeBinding = ASTNodes.getTypeBinding(astRoot, type);
if (typeBinding == null) {
return new CheckDelegateMethodsResponse();
}
DelegateEntry[] delegateEntries = StubUtility2Core.getDelegatableMethods(typeBinding);
Map<IVariableBinding, List<IMethodBinding>> fieldToMethods = new LinkedHashMap<>();
for (DelegateEntry delegateEntry : delegateEntries) {
List<IMethodBinding> methods = fieldToMethods.getOrDefault(delegateEntry.field, new ArrayList<>());
methods.add(delegateEntry.delegateMethod);
fieldToMethods.put(delegateEntry.field, methods);
}
//@formatter:off
return new CheckDelegateMethodsResponse(fieldToMethods.entrySet().stream()
.map(entry -> new LspDelegateField(entry.getKey(), entry.getValue().toArray(new IMethodBinding[0])))
.toArray(LspDelegateField[]::new));
//@formatter:on
} catch (JavaModelException e) {
JavaLanguageServerPlugin.logException("Failed to check delegate methods status", e);
}
return new CheckDelegateMethodsResponse();
}
@Override
SourceActionDialog createDialog(Shell shell, IType type) throws JavaModelException {
IVariableBinding[] fieldBindings= fFields.toArray(new IVariableBinding[0]);
IVariableBinding[] inheritedFieldBindings= fInheritedFields.toArray(new IVariableBinding[0]);
IVariableBinding[] selectedFieldBindings= fSelectedFields.toArray(new IVariableBinding[0]);
IMethodBinding[] methodBindings= fMethods.toArray(new IMethodBinding[0]);
IMethodBinding[] inheritededMethodBindings= fInheritedMethods.toArray(new IMethodBinding[0]);
return new GenerateToStringDialog(shell, fEditor, type, fieldBindings, inheritedFieldBindings, selectedFieldBindings, methodBindings, inheritededMethodBindings);
}
private static void checkName(RefactoringStatus status, String name, List<IMethodBinding> usedNames, IType type, boolean reUseExistingField, IField field) {
if ("".equals(name)) { //$NON-NLS-1$
status.addFatalError(RefactoringCoreMessages.Checks_Choose_name);
return;
}
boolean isStatic=false;
try {
isStatic= Flags.isStatic(field.getFlags());
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
status.merge(Checks.checkMethodName(name, field));
for (Iterator<IMethodBinding> iter= usedNames.iterator(); iter.hasNext(); ) {
IMethodBinding method= iter.next();
String selector= method.getName();
if (selector.equals(name)) {
if (!reUseExistingField) {
status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_method_exists, new String[] { BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(type.getElementName()) }));
} else {
boolean methodIsStatic= Modifier.isStatic(method.getModifiers());
if (methodIsStatic && !isStatic)
status.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
if (!methodIsStatic && isStatic)
status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
return;
}
}
}
if (reUseExistingField)
status.addFatalError(Messages.format(
RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError,
new String[] { BasicElementLabels.getJavaElementName(name), BasicElementLabels.getJavaElementName(type.getElementName())}));
}
private Collection<ITypeConstraint> getConstraintsForOverriding(IMethodBinding overridingMethod) {
Collection<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
Set<ITypeBinding> declaringSupertypes= getDeclaringSuperTypes(overridingMethod);
for (Iterator<ITypeBinding> iter= declaringSupertypes.iterator(); iter.hasNext();) {
ITypeBinding superType= iter.next();
IMethodBinding overriddenMethod= findMethod(overridingMethod, superType);
Assert.isNotNull(overriddenMethod);//because we asked for declaring types
if (Bindings.equals(overridingMethod, overriddenMethod))
continue;
ITypeConstraint[] returnTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
fConstraintVariableFactory.makeReturnTypeVariable(overriddenMethod),
fConstraintVariableFactory.makeReturnTypeVariable(overridingMethod));
result.addAll(Arrays.asList(returnTypeConstraint));
Assert.isTrue(overriddenMethod.getParameterTypes().length == overridingMethod.getParameterTypes().length);
for (int i= 0, n= overriddenMethod.getParameterTypes().length; i < n; i++) {
ITypeConstraint[] parameterTypeConstraint= fTypeConstraintFactory.createEqualsConstraint(
fConstraintVariableFactory.makeParameterTypeVariable(overriddenMethod, i),
fConstraintVariableFactory.makeParameterTypeVariable(overridingMethod, i));
result.addAll(Arrays.asList(parameterTypeConstraint));
}
ITypeConstraint[] declaringTypeConstraint= fTypeConstraintFactory.createStrictSubtypeConstraint(
fConstraintVariableFactory.makeDeclaringTypeVariable(overridingMethod),
fConstraintVariableFactory.makeDeclaringTypeVariable(overriddenMethod));
result.addAll(Arrays.asList(declaringTypeConstraint));
}
return result;
}