下面列出了org.eclipse.jdt.core.dom.CreationReference#org.eclipse.jdt.internal.corext.dom.Bindings 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public boolean consumes(SemanticToken token) {
SimpleName node= token.getNode();
if (node.isDeclaration())
return false;
IBinding binding= token.getBinding();
if (binding == null || binding.getKind() != IBinding.METHOD)
return false;
ITypeBinding currentType= Bindings.getBindingOfParentType(node);
ITypeBinding declaringType= ((IMethodBinding) binding).getDeclaringClass();
if (currentType == declaringType || currentType == null)
return false;
return Bindings.isSuperType(declaringType, currentType);
}
/**
* Opens and reveals the defining method.
*/
public void open() {
CompilationUnit ast= SharedASTProvider.getAST(fJavaElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
if (ast != null) {
ASTNode node= ast.findDeclaringNode(fAstNodeKey);
if (node instanceof MethodDeclaration) {
try {
IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
IMethodBinding definingMethodBinding= Bindings.findOverriddenMethod(methodBinding, true);
if (definingMethodBinding != null) {
IJavaElement definingMethod= definingMethodBinding.getJavaElement();
if (definingMethod != null) {
JavaUI.openInEditor(definingMethod, true, true);
return;
}
}
} catch (CoreException e) {
ExceptionHandler.handle(e, JavaEditorMessages.OverrideIndicatorManager_open_error_title, JavaEditorMessages.OverrideIndicatorManager_open_error_messageHasLogEntry);
return;
}
}
}
String title= JavaEditorMessages.OverrideIndicatorManager_open_error_title;
String message= JavaEditorMessages.OverrideIndicatorManager_open_error_message;
MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
private static IMethodBinding[] getDelegateCandidates(ITypeBinding binding, ITypeBinding hierarchy) {
List<IMethodBinding> allMethods= new ArrayList<IMethodBinding>();
boolean isInterface= binding.isInterface();
IMethodBinding[] typeMethods= binding.getDeclaredMethods();
for (int index= 0; index < typeMethods.length; index++) {
final int modifiers= typeMethods[index].getModifiers();
if (!typeMethods[index].isConstructor() && !Modifier.isStatic(modifiers) && (isInterface || Modifier.isPublic(modifiers))) {
IMethodBinding result= Bindings.findOverriddenMethodInHierarchy(hierarchy, typeMethods[index]);
if (result != null && Flags.isFinal(result.getModifiers()))
continue;
ITypeBinding[] parameterBindings= typeMethods[index].getParameterTypes();
boolean upper= false;
for (int offset= 0; offset < parameterBindings.length; offset++) {
if (parameterBindings[offset].isWildcardType() && parameterBindings[offset].isUpperbound())
upper= true;
}
if (!upper)
allMethods.add(typeMethods[index]);
}
}
return allMethods.toArray(new IMethodBinding[allMethods.size()]);
}
private static boolean supportsExtractVariable(IInvocationContext context) {
ASTNode node = context.getCoveredNode();
if (!(node instanceof Expression)) {
if (context.getSelectionLength() != 0) {
return false;
}
node = context.getCoveringNode();
if (!(node instanceof Expression)) {
return false;
}
}
final Expression expression = (Expression) node;
ITypeBinding binding = expression.resolveTypeBinding();
if (binding == null || Bindings.isVoidType(binding)) {
return false;
}
return true;
}
private Statement createAddArrayHashCode(IVariableBinding binding) {
MethodInvocation invoc= fAst.newMethodInvocation();
if (JavaModelUtil.is50OrHigher(fRewrite.getCu().getJavaProject())) {
invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS));
invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
} else {
invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
final IJavaElement element= fType.getJavaElement();
if (element != null && !"".equals(element.getElementName())) //$NON-NLS-1$
invoc.setExpression(fAst.newSimpleName(element.getElementName()));
invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
ITypeBinding type= binding.getType().getElementType();
if (!Bindings.isVoidType(type)) {
if (!type.isPrimitive() || binding.getType().getDimensions() >= 2)
type= fAst.resolveWellKnownType(JAVA_LANG_OBJECT);
if (!fCustomHashCodeTypes.contains(type))
fCustomHashCodeTypes.add(type);
}
}
return prepareAssignment(invoc);
}
private boolean considerBinding(IBinding binding, ASTNode node) {
if (!(binding instanceof IVariableBinding)) {
return false;
}
boolean result = Bindings.equals(fFieldBinding, ((IVariableBinding) binding).getVariableDeclaration());
if (!result || fEncapsulateDeclaringClass) {
return result;
}
if (binding instanceof IVariableBinding) {
AbstractTypeDeclaration type = ASTNodes.getParent(node, AbstractTypeDeclaration.class);
if (type != null) {
ITypeBinding declaringType = type.resolveBinding();
return !Bindings.equals(fDeclaringClassBinding, declaringType);
}
}
return true;
}
public ITypeBinding getTypeBinding(AST ast) {
boolean couldBeObject= false;
for (int i= 0; i < fResult.size(); i++) {
ReturnStatement node= fResult.get(i);
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding != null) {
return binding;
} else {
couldBeObject= true;
}
} else {
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
}
if (couldBeObject) {
return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
@Override
protected Expression computeProposals(AST ast, ITypeBinding returnBinding, int returnOffset, CompilationUnit root, Expression result) {
ScopeAnalyzer analyzer= new ScopeAnalyzer(root);
IBinding[] bindings= analyzer.getDeclarationsInScope(returnOffset, ScopeAnalyzer.VARIABLES | ScopeAnalyzer.CHECK_VISIBILITY);
org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(root, returnOffset, 0);
ASTNode varDeclFrag= ASTResolving.findAncestor(finder.getCoveringNode(), ASTNode.VARIABLE_DECLARATION_FRAGMENT);
IVariableBinding varDeclFragBinding= null;
if (varDeclFrag != null) {
varDeclFragBinding= ((VariableDeclarationFragment) varDeclFrag).resolveBinding();
}
for (int i= 0; i < bindings.length; i++) {
IVariableBinding curr= (IVariableBinding) bindings[i];
ITypeBinding type= curr.getType();
// Bindings are compared to make sure that a lambda does not return a variable which is yet to be initialised.
if (type != null && type.isAssignmentCompatible(returnBinding) && testModifier(curr) && !Bindings.equals(curr, varDeclFragBinding)) {
if (result == null) {
result= ast.newSimpleName(curr.getName());
}
addLinkedPositionProposal(RETURN_EXPRESSION_KEY, curr.getName());
}
}
return result;
}
private ITypeBinding getEnclosingInstance() {
ITypeBinding currBinding= fTypeNode.resolveBinding();
if (currBinding == null || Modifier.isStatic(currBinding.getModifiers())) {
return null;
}
ITypeBinding superBinding= currBinding.getSuperclass();
if (superBinding == null || superBinding.getDeclaringClass() == null || Modifier.isStatic(superBinding.getModifiers())) {
return null;
}
ITypeBinding enclosing= superBinding.getDeclaringClass();
while (currBinding != null) {
if (Bindings.isSuperType(enclosing, currBinding)) {
return null; // enclosing in scope
}
if (Modifier.isStatic(currBinding.getModifiers())) {
return null; // no more enclosing instances
}
currBinding= currBinding.getDeclaringClass();
}
return enclosing;
}
private static String getExpressionBaseName(Expression expr) {
IBinding argBinding= Bindings.resolveExpressionBinding(expr, true);
if (argBinding instanceof IVariableBinding) {
IJavaProject project= null;
ASTNode root= expr.getRoot();
if (root instanceof CompilationUnit) {
ITypeRoot typeRoot= ((CompilationUnit) root).getTypeRoot();
if (typeRoot != null) {
project= typeRoot.getJavaProject();
}
}
return StubUtility.getBaseName((IVariableBinding)argBinding, project);
}
if (expr instanceof SimpleName) {
return ((SimpleName) expr).getIdentifier();
}
return null;
}
@Override
public boolean consumes(final SemanticToken token) {
final SimpleName node= token.getNode();
if (node.isDeclaration()) {
return false;
}
final IBinding binding= token.getBinding();
if (binding == null || binding.getKind() != IBinding.VARIABLE) {
return false;
}
ITypeBinding currentType= Bindings.getBindingOfParentType(node);
ITypeBinding declaringType= ((IVariableBinding) binding).getDeclaringClass();
if (declaringType == null || currentType == declaringType)
return false;
return Bindings.isSuperType(declaringType, currentType);
}
@Override
protected List<CategorizedProblem> doValidateMethodOnDependentInterface(
IMethodBinding methodBinding, TypeDeclaration changedInterface,
ITypeBinding dependentInterfaceBinding) {
String[] parameters = RemoteServiceUtilities.computeAsyncParameterTypes(methodBinding);
String methodName = methodBinding.getName();
if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(),
methodName, parameters) == null) {
CategorizedProblem problem = RemoteServiceProblemFactory.newMissingAsyncMethodOnAsync(
methodBinding, changedInterface);
if (problem != null) {
return Collections.singletonList(problem);
}
}
return Collections.emptyList();
}
public static List<IMethodBinding> computeSyncMethodsThatNeedAsyncVersions(
ITypeBinding syncTypeBinding, ITypeBinding asyncTypeBinding) {
// Compute all overridable methods on the sync interface
List<IMethodBinding> overridableSyncMethods = computeOverridableMethodsForInterface(syncTypeBinding);
// Remove sync methods that would override existing methods in the
// async hierarchy
List<IMethodBinding> remainingMethods = new ArrayList<IMethodBinding>();
for (IMethodBinding overridableSyncMethod : overridableSyncMethods) {
IMethod syncMethod = (IMethod) overridableSyncMethod.getJavaElement();
String[] asyncParameterTypes = RemoteServiceUtilities.computeAsyncParameterTypes(overridableSyncMethod);
if (Bindings.findMethodInHierarchy(asyncTypeBinding,
syncMethod.getElementName(), asyncParameterTypes) != null) {
// Don't add method that appear in the type hierarchy
continue;
}
remainingMethods.add(overridableSyncMethod);
}
return remainingMethods;
}
private static int getNeededVisibility(ASTNode currNode, ITypeBinding targetType, IBinding binding) {
ITypeBinding currNodeBinding= Bindings.getBindingOfParentType(currNode);
if (currNodeBinding == null) { // import
return Modifier.PUBLIC;
}
if (Bindings.isSuperType(targetType, currNodeBinding)) {
if (binding != null && (JdtFlags.isProtected(binding) || binding.getKind() == IBinding.TYPE)) {
return Modifier.PUBLIC;
}
return Modifier.PROTECTED;
}
if (currNodeBinding.getPackage().getKey().equals(targetType.getPackage().getKey())) {
return 0;
}
return Modifier.PUBLIC;
}
@Override
public boolean visit(final ThisExpression node) {
Assert.isNotNull(node);
Name name= node.getQualifier();
if (fCreateInstanceField && name != null) {
ITypeBinding binding= node.resolveTypeBinding();
if (binding != null && Bindings.equals(binding, fTypeBinding.getDeclaringClass())) {
AST ast= node.getAST();
Expression expression= null;
if (fCodeGenerationSettings.useKeywordThis || fEnclosingInstanceFieldName.equals(fNameForEnclosingInstanceConstructorParameter)) {
FieldAccess access= ast.newFieldAccess();
access.setExpression(ast.newThisExpression());
access.setName(ast.newSimpleName(fEnclosingInstanceFieldName));
expression= access;
} else {
expression= ast.newSimpleName(fEnclosingInstanceFieldName);
}
fSourceRewrite.getASTRewrite().replace(node, expression, null);
}
}
return super.visit(node);
}
public ParameterTypeVariable2 makeParameterTypeVariable(IMethodBinding methodBinding, int parameterIndex) {
if (methodBinding == null)
return null;
TType type= getBoxedType(methodBinding.getParameterTypes() [parameterIndex], /*no boxing*/null);
if (type == null)
return null;
ParameterTypeVariable2 cv= new ParameterTypeVariable2(type, parameterIndex, methodBinding);
ParameterTypeVariable2 storedCv= (ParameterTypeVariable2) storedCv(cv);
if (storedCv == cv) {
if (methodBinding.getDeclaringClass().isLocal() || Modifier.isPrivate(methodBinding.getModifiers()))
fCuScopedConstraintVariables.add(cv);
makeElementVariables(storedCv, type);
makeArrayElementVariable(storedCv);
if (fStoreToString)
storedCv.setData(ConstraintVariable2.TO_STRING, "[Parameter(" + parameterIndex + "," + Bindings.asString(methodBinding) + ")]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
return storedCv;
}
@Override
public final boolean visit(final QualifiedName node) {
Assert.isNotNull(node);
IBinding binding= node.resolveBinding();
if (binding instanceof ITypeBinding) {
final ITypeBinding type= (ITypeBinding) binding;
if (type.isClass() && type.getDeclaringClass() != null) {
final Type newType= fTargetRewrite.getImportRewrite().addImport(type, node.getAST());
fRewrite.replace(node, newType, null);
return false;
}
}
binding= node.getQualifier().resolveBinding();
if (Bindings.equals(fTarget, binding)) {
fRewrite.replace(node, getFieldReference(node.getName(), fRewrite), null);
return false;
}
node.getQualifier().accept(this);
return false;
}
/**
* Checks if the new method is already used in the given type.
* @param type
* @param methodName
* @param parameters
* @return the status
*/
public static RefactoringStatus checkMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
RefactoringStatus result= new RefactoringStatus();
IMethodBinding method= org.eclipse.jdt.internal.corext.dom.Bindings.findMethodInType(type, methodName, parameters);
if (method != null) {
if (method.isConstructor()) {
result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
new Object[] { BasicElementLabels.getJavaElementName(type.getName()) }));
} else {
result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists,
new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(type.getName()) }),
JavaStatusContext.create(method));
}
}
return result;
}
private boolean matches(ITypeBinding exception) {
if (exception == null)
return false;
if (isCaught(exception))
return false;
while (exception != null) {
if (Bindings.equals(fException, exception))
return true;
exception= exception.getSuperclass();
}
return false;
}
@Override
public boolean visit(SimpleName node) {
if(!fResult) {
fResult= Bindings.equals(fBinding, node.resolveBinding());
}
return false;
}
private static void addNewFieldProposals(ICompilationUnit cu, CompilationUnit astRoot, ITypeBinding binding, ITypeBinding declaringTypeBinding, SimpleName simpleName, boolean isWriteAccess, Collection<ICommandAccess> proposals) throws JavaModelException {
// new variables
ICompilationUnit targetCU;
ITypeBinding senderDeclBinding;
if (binding != null) {
senderDeclBinding= binding.getTypeDeclaration();
targetCU= ASTResolving.findCompilationUnitForBinding(cu, astRoot, senderDeclBinding);
} else { // binding is null for accesses without qualifier
senderDeclBinding= declaringTypeBinding;
targetCU= cu;
}
if (!senderDeclBinding.isFromSource() || targetCU == null) {
return;
}
boolean mustBeConst= ASTResolving.isInsideModifiers(simpleName);
addNewFieldForType(targetCU, binding, senderDeclBinding, simpleName, isWriteAccess, mustBeConst, proposals);
if (binding == null && senderDeclBinding.isNested()) {
ASTNode anonymDecl= astRoot.findDeclaringNode(senderDeclBinding);
if (anonymDecl != null) {
ITypeBinding bind= Bindings.getBindingOfParentType(anonymDecl.getParent());
if (!bind.isAnonymous()) {
addNewFieldForType(targetCU, bind, bind, simpleName, isWriteAccess, mustBeConst, proposals);
}
}
}
}
/**
* Proposes a setter for this field.
*
* @param context the proposal parameter
* @param relevance relevance of this proposal
* @return the proposal if available or null
*/
private static ChangeCorrectionProposal addSetterProposal(ProposalParameter context, int relevance) {
boolean isBoolean= isBoolean(context);
String setterName= GetterSetterUtil.getSetterName(context.variableBinding, context.compilationUnit.getJavaProject(), null, isBoolean);
ITypeBinding declaringType= context.variableBinding.getDeclaringClass();
if (declaringType == null)
return null;
IMethodBinding method= Bindings.findMethodInHierarchy(declaringType, setterName, new ITypeBinding[] { context.variableBinding.getType() });
if (method != null && Bindings.isVoidType(method.getReturnType()) && (Modifier.isStatic(method.getModifiers()) == Modifier.isStatic(context.variableBinding.getModifiers()))) {
Expression assignedValue= getAssignedValue(context);
if (assignedValue == null)
return null; //we don't know how to handle those cases.
Expression mi= createMethodInvocation(context, method, assignedValue);
context.astRewrite.replace(context.accessNode.getParent(), mi, null);
String label= Messages.format(CorrectionMessages.GetterSetterCorrectionSubProcessor_replacewithsetter_description, BasicElementLabels.getJavaCodeString(ASTNodes.asString(context.accessNode)));
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.compilationUnit, context.astRewrite, relevance, image);
return proposal;
} else {
IJavaElement element= context.variableBinding.getJavaElement();
if (element instanceof IField) {
IField field= (IField) element;
try {
if (RefactoringAvailabilityTester.isSelfEncapsulateAvailable(field))
return new SelfEncapsulateFieldProposal(relevance, field);
} catch (JavaModelException e) {
JavaPlugin.log(e);
}
}
}
return null;
}
private static boolean getAssignAllParamsToFieldsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
node = ASTNodes.getNormalizedNode(node);
ASTNode parent = node.getParent();
if (!(parent instanceof SingleVariableDeclaration) || !(parent.getParent() instanceof MethodDeclaration)) {
return false;
}
MethodDeclaration methodDecl = (MethodDeclaration) parent.getParent();
if (methodDecl.getBody() == null) {
return false;
}
List<SingleVariableDeclaration> parameters = methodDecl.parameters();
if (parameters.size() <= 1) {
return false;
}
ITypeBinding parentType = Bindings.getBindingOfParentType(node);
if (parentType == null || parentType.isInterface()) {
return false;
}
for (SingleVariableDeclaration param : parameters) {
IVariableBinding binding = param.resolveBinding();
if (binding == null || binding.getType() == null) {
return false;
}
}
if (resultingCollections == null) {
return true;
}
AssignToVariableAssistProposal fieldProposal = new AssignToVariableAssistProposal(context.getCompilationUnit(), parameters, IProposalRelevance.ASSIGN_ALL_PARAMS_TO_NEW_FIELDS);
resultingCollections.add(fieldProposal);
return true;
}
private TType getBoxedType(ITypeBinding typeBinding, Expression expression) {
if (typeBinding == null)
return null;
if (! typeBinding.isPrimitive())
return createTType(typeBinding);
if (expression == null || ! expression.resolveBoxing())
return null;
ITypeBinding boxed= Bindings.getBoxedTypeBinding(typeBinding, expression.getAST());
return createTType(boxed);
}
public static ITypeBinding boxUnboxPrimitives(ITypeBinding castType, ITypeBinding toCast, AST ast) {
/*
* e.g:
* void m(toCast var) {
* castType i= var;
* }
*/
if (castType.isPrimitive() && !toCast.isPrimitive()) {
return Bindings.getBoxedTypeBinding(castType, ast);
} else if (!castType.isPrimitive() && toCast.isPrimitive()) {
return Bindings.getUnboxedTypeBinding(castType, ast);
} else {
return castType;
}
}
public static CUCorrectionProposal getAssignFieldProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
IProblemLocationCore[] locations) throws CoreException {
ASTNode node = context.getCoveringNode();
Statement statement = ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return null;
}
ExpressionStatement expressionStatement = (ExpressionStatement) statement;
Expression expression = expressionStatement.getExpression();
if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
return null;
}
ITypeBinding typeBinding = expression.resolveTypeBinding();
typeBinding = Bindings.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return null;
}
if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
return null;
}
final ICompilationUnit cu = context.getCompilationUnit();
ASTNode type = ASTResolving.findParentType(expression);
if (type != null) {
int relevance;
if (context.getSelectionLength() == 0) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
} else if (problemsAtLocation) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
} else {
relevance = IProposalRelevance.EXTRACT_LOCAL;
}
if (returnAsCommand) {
return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
Arrays.asList(ASSIGN_FIELD_COMMAND, params));
} else {
return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance);
}
}
return null;
}
@Override
public boolean visit(MethodInvocation node) {
Expression receiver = node.getExpression();
if (receiver == null) {
SimpleName name = node.getName();
if (fIgnoreBinding == null || !Bindings.equals(fIgnoreBinding, name.resolveBinding())) {
node.getName().accept(this);
}
} else {
receiver.accept(this);
}
accept(node.arguments());
return false;
}
@Override
public boolean match(SimpleName candidate, Object s) {
if (!(s instanceof SimpleName)) {
return false;
}
SimpleName snippet = (SimpleName) s;
if (candidate.isDeclaration() != snippet.isDeclaration()) {
return false;
}
IBinding cb = candidate.resolveBinding();
IBinding sb = snippet.resolveBinding();
if (cb == null || sb == null) {
return false;
}
IVariableBinding vcb = ASTNodes.getVariableBinding(candidate);
IVariableBinding vsb = ASTNodes.getVariableBinding(snippet);
if (vcb == null || vsb == null) {
return Bindings.equals(cb, sb);
}
if (!vcb.isField() && !vsb.isField() && Bindings.equals(vcb.getType(), vsb.getType())) {
SimpleName mapped = fMatch.getMappedName(vsb);
if (mapped != null) {
IVariableBinding mappedBinding = ASTNodes.getVariableBinding(mapped);
if (!Bindings.equals(vcb, mappedBinding)) {
return false;
}
}
fMatch.addLocal(vsb, candidate);
return true;
}
return Bindings.equals(cb, sb);
}
private RefactoringStatus checkTempTypeForLocalTypeUsage() throws JavaModelException {
Expression expression = getSelectedExpression().getAssociatedExpression();
Type resultingType = null;
ITypeBinding typeBinding = expression.resolveTypeBinding();
AST ast = fCURewrite.getAST();
if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
resultingType = ((ClassInstanceCreation) expression).getType();
} else if (expression instanceof CastExpression) {
resultingType = ((CastExpression) expression).getType();
} else {
if (typeBinding == null) {
typeBinding = ASTResolving.guessBindingForReference(expression);
}
if (typeBinding != null) {
typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
ImportRewrite importRewrite = fCURewrite.getImportRewrite();
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
resultingType = importRewrite.addImport(typeBinding, ast, context, TypeLocation.LOCAL_VARIABLE);
} else {
resultingType = ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
}
}
IMethodBinding declaringMethodBinding = getMethodDeclaration().resolveBinding();
ITypeBinding[] methodTypeParameters = declaringMethodBinding == null ? new ITypeBinding[0] : declaringMethodBinding.getTypeParameters();
LocalTypeAndVariableUsageAnalyzer analyzer = new LocalTypeAndVariableUsageAnalyzer(methodTypeParameters);
resultingType.accept(analyzer);
boolean usesLocalTypes = !analyzer.getUsageOfEnclosingNodes().isEmpty();
if (usesLocalTypes) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractFieldRefactoring_uses_type_declared_locally);
}
return null;
}
/**
* Checks if the new method somehow conflicts with an already existing method in
* the hierarchy. The following checks are done:
* <ul>
* <li> if the new method overrides a method defined in the given type or in one of its
* super classes. </li>
* </ul>
* @param type
* @param methodName
* @param returnType
* @param parameters
* @return the status
*/
public static RefactoringStatus checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters) {
RefactoringStatus result= new RefactoringStatus();
IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
if (method != null) {
boolean returnTypeClash= false;
ITypeBinding methodReturnType= method.getReturnType();
if (returnType != null && methodReturnType != null) {
String returnTypeKey= returnType.getKey();
String methodReturnTypeKey= methodReturnType.getKey();
if (returnTypeKey == null && methodReturnTypeKey == null) {
returnTypeClash= returnType != methodReturnType;
} else if (returnTypeKey != null && methodReturnTypeKey != null) {
returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
}
}
ITypeBinding dc= method.getDeclaringClass();
if (returnTypeClash) {
result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
JavaStatusContext.create(method));
} else {
if (method.isConstructor()) {
result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
new Object[] { BasicElementLabels.getJavaElementName(dc.getName()) }));
} else {
result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName()) }),
JavaStatusContext.create(method));
}
}
}
return result;
}