下面列出了怎么用org.eclipse.jdt.core.dom.IBinding的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean checkName(Name name) {
IBinding binding = name.resolveBinding();
if (binding == null) {
return true; /* If the binding is null because of compile errors etc.,
scenarios which may have been deemed unacceptable in
the presence of semantic information will be admitted. */
}
// If name represents a member:
if (binding instanceof IVariableBinding || binding instanceof IMethodBinding) {
return isMemberReferenceValidInClassInitialization(name);
} else if (binding instanceof ITypeBinding) {
return !((ITypeBinding) binding).isTypeVariable();
} else {
return true; // e.g. a NameQualifiedType's qualifier, which can be a package binding
}
}
@Override
public boolean consumes(SemanticToken token) {
// 1: match types
SimpleName name= token.getNode();
ASTNode node= name.getParent();
int nodeType= node.getNodeType();
if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.THIS_EXPRESSION && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION && nodeType != ASTNode.METHOD_INVOCATION)
return false;
while (nodeType == ASTNode.QUALIFIED_NAME) {
node= node.getParent();
nodeType= node.getNodeType();
if (nodeType == ASTNode.IMPORT_DECLARATION)
return false;
}
// 2: match classes
IBinding binding= token.getBinding();
return binding instanceof ITypeBinding && ((ITypeBinding) binding).isClass();
}
private static String getDisplayString(SimpleName simpleName, IBinding binding, boolean removeAllAssignements) {
String name= BasicElementLabels.getJavaElementName(simpleName.getIdentifier());
switch (binding.getKind()) {
case IBinding.TYPE:
return Messages.format(FixMessages.UnusedCodeFix_RemoveType_description, name);
case IBinding.METHOD:
if (((IMethodBinding) binding).isConstructor()) {
return Messages.format(FixMessages.UnusedCodeFix_RemoveConstructor_description, name);
} else {
return Messages.format(FixMessages.UnusedCodeFix_RemoveMethod_description, name);
}
case IBinding.VARIABLE:
if (removeAllAssignements) {
return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocalWithInitializer_description, name);
} else {
return Messages.format(FixMessages.UnusedCodeFix_RemoveFieldOrLocal_description, name);
}
default:
return ""; //$NON-NLS-1$
}
}
@Override
public void endVisit(SimpleName node) {
if (skipNode(node) || node.isDeclaration())
return;
IBinding binding= node.resolveBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding variable= (IVariableBinding)binding;
if (!variable.isField()) {
setFlowInfo(node, new LocalFlowInfo(
variable,
FlowInfo.READ,
fFlowContext));
}
} else if (binding instanceof ITypeBinding) {
ITypeBinding type= (ITypeBinding)binding;
if (type.isTypeVariable()) {
setFlowInfo(node, new TypeVariableFlowInfo(type, fFlowContext));
}
}
}
@Override
public boolean consumes(SemanticToken token) {
// 1: match types
SimpleName name= token.getNode();
ASTNode node= name.getParent();
int nodeType= node.getNodeType();
if (nodeType != ASTNode.METHOD_INVOCATION && nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME
&& nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.ENUM_DECLARATION)
return false;
while (nodeType == ASTNode.QUALIFIED_NAME) {
node= node.getParent();
nodeType= node.getNodeType();
if (nodeType == ASTNode.IMPORT_DECLARATION)
return false;
}
// 2: match enums
IBinding binding= token.getBinding();
return binding instanceof ITypeBinding && ((ITypeBinding) binding).isEnum();
}
public IBinding[] getDeclarationsAfter(int offset, int flags) {
try {
org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
ASTNode node= finder.getCoveringNode();
if (node == null) {
return null;
}
ASTNode declaration= ASTResolving.findParentStatement(node);
while (declaration instanceof Statement && declaration.getNodeType() != ASTNode.BLOCK) {
declaration= declaration.getParent();
}
if (declaration instanceof Block) {
DefaultBindingRequestor requestor= new DefaultBindingRequestor();
DeclarationsAfterVisitor visitor= new DeclarationsAfterVisitor(node.getStartPosition(), flags, requestor);
declaration.accept(visitor);
List<IBinding> result= requestor.getResult();
return result.toArray(new IBinding[result.size()]);
}
return NO_BINDING;
} finally {
clearLists();
}
}
private Expression convert(org.eclipse.jdt.core.dom.QualifiedName expression) {
IBinding binding = expression.resolveBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding variableBinding = (IVariableBinding) binding;
checkArgument(
variableBinding.isField(),
internalCompilerErrorMessage("Unexpected QualifiedName that is not a field"));
Expression qualifier = convert(expression.getQualifier());
return JdtUtils.createFieldAccess(qualifier, variableBinding);
}
if (binding instanceof ITypeBinding) {
return null;
}
throw internalCompilerError(
"Unexpected type for QualifiedName binding: %s ", binding.getClass().getName());
}
public IBinding[] getDeclarationsInScope(int offset, int flags) {
org.eclipse.jdt.core.dom.NodeFinder finder= new org.eclipse.jdt.core.dom.NodeFinder(fRoot, offset, 0);
ASTNode node= finder.getCoveringNode();
if (node == null) {
return NO_BINDING;
}
if (node instanceof SimpleName) {
return getDeclarationsInScope((SimpleName) node, flags);
}
try {
ITypeBinding binding= Bindings.getBindingOfParentType(node);
DefaultBindingRequestor requestor= new DefaultBindingRequestor(binding, flags);
addLocalDeclarations(node, offset, flags, requestor);
if (binding != null) {
addTypeDeclarations(binding, flags, requestor);
}
List<IBinding> result= requestor.getResult();
return result.toArray(new IBinding[result.size()]);
} finally {
clearLists();
}
}
private static boolean canModifyAccessRules(IBinding binding) {
IJavaElement element= binding.getJavaElement();
if (element == null)
return false;
IPackageFragmentRoot root= JavaModelUtil.getPackageFragmentRoot(element);
if (root == null)
return false;
try {
IClasspathEntry classpathEntry= root.getRawClasspathEntry();
if (classpathEntry == null)
return false;
if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_LIBRARY)
return true;
if (classpathEntry.getEntryKind() == IClasspathEntry.CPE_CONTAINER) {
ClasspathContainerInitializer classpathContainerInitializer= JavaCore.getClasspathContainerInitializer(classpathEntry.getPath().segment(0));
IStatus status= classpathContainerInitializer.getAccessRulesStatus(classpathEntry.getPath(), root.getJavaProject());
return status.isOK();
}
} catch (JavaModelException e) {
return false;
}
return false;
}
@Override
public boolean visit(SimpleName node) {
IBinding binding= node.resolveBinding();
if (fBinding == binding) {
String groupDescription= null;
if (node != fName) {
if (fUpdateReferences) {
groupDescription= RefactoringCoreMessages.RenameTypeParameterRefactoring_update_type_parameter_reference;
}
} else {
groupDescription= RefactoringCoreMessages.RenameTypeParameterRefactoring_update_type_parameter_declaration;
}
if (groupDescription != null) {
fRewrite.getASTRewrite().set(node, SimpleName.IDENTIFIER_PROPERTY, getNewElementName(), fRewrite.createGroupDescription(groupDescription));
}
}
return true;
}
/**
* Is the specified name a target access?
*
* @param name
* the name to check
* @return <code>true</code> if this name is a target access,
* <code>false</code> otherwise
*/
protected boolean isTargetAccess(final Name name) {
Assert.isNotNull(name);
final IBinding binding= name.resolveBinding();
if (Bindings.equals(fTarget, binding))
return true;
if (name.getParent() instanceof FieldAccess) {
final FieldAccess access= (FieldAccess) name.getParent();
final Expression expression= access.getExpression();
if (expression instanceof Name)
return isTargetAccess((Name) expression);
} else if (name instanceof QualifiedName) {
final QualifiedName qualified= (QualifiedName) name;
if (qualified.getQualifier() != null)
return isTargetAccess(qualified.getQualifier());
}
return false;
}
public static IBinding resolveBinding(Expression expression){
if (expression instanceof Name)
return ((Name)expression).resolveBinding();
if (expression instanceof ParenthesizedExpression)
return resolveBinding(((ParenthesizedExpression)expression).getExpression());
else if (expression instanceof Assignment)
return resolveBinding(((Assignment)expression).getLeftHandSide());//TODO ???
else if (expression instanceof MethodInvocation)
return ((MethodInvocation)expression).resolveMethodBinding();
else if (expression instanceof SuperMethodInvocation)
return ((SuperMethodInvocation)expression).resolveMethodBinding();
else if (expression instanceof FieldAccess)
return ((FieldAccess)expression).resolveFieldBinding();
else if (expression instanceof SuperFieldAccess)
return ((SuperFieldAccess)expression).resolveFieldBinding();
else if (expression instanceof ConditionalExpression)
return resolveBinding(((ConditionalExpression)expression).getThenExpression());
return null;
}
@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);
}
@Override
public boolean consumes(SemanticToken token) {
// 1: match types
SimpleName name = token.getNode();
ASTNode node = name.getParent();
int nodeType = node.getNodeType();
if (nodeType != ASTNode.METHOD_INVOCATION && nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.QUALIFIED_NAME
&& nodeType != ASTNode.ENUM_DECLARATION) {
return false;
}
while (nodeType == ASTNode.QUALIFIED_NAME) {
node = node.getParent();
nodeType = node.getNodeType();
if (nodeType == ASTNode.IMPORT_DECLARATION) {
return false;
}
}
// 2: match enums
IBinding binding = token.getBinding();
return binding instanceof ITypeBinding && ((ITypeBinding) binding).isEnum();
}
@Override
public boolean consumes(SemanticToken token) {
// 1: match types
SimpleName name = token.getNode();
ASTNode node = name.getParent();
int nodeType = node.getNodeType();
if (nodeType != ASTNode.SIMPLE_TYPE && nodeType != ASTNode.QUALIFIED_TYPE && nodeType != ASTNode.QUALIFIED_NAME && nodeType != ASTNode.TYPE_DECLARATION) {
return false;
}
while (nodeType == ASTNode.QUALIFIED_NAME) {
node = node.getParent();
nodeType = node.getNodeType();
if (nodeType == ASTNode.IMPORT_DECLARATION) {
return false;
}
}
// 2: match interfaces
IBinding binding = token.getBinding();
return binding instanceof ITypeBinding && ((ITypeBinding) binding).isInterface();
}
private static Map<String, String> getCleanUpOptions(IBinding binding, boolean removeAll) {
Map<String, String> result= new Hashtable<String, String>();
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_MEMBERS, CleanUpOptions.TRUE);
switch (binding.getKind()) {
case IBinding.TYPE:
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_TYPES, CleanUpOptions.TRUE);
break;
case IBinding.METHOD:
if (((IMethodBinding) binding).isConstructor()) {
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_CONSTRUCTORS, CleanUpOptions.TRUE);
} else {
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_METHODS, CleanUpOptions.TRUE);
}
break;
case IBinding.VARIABLE:
if (removeAll)
return null;
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_PRIVATE_FELDS, CleanUpOptions.TRUE);
result.put(CleanUpConstants.REMOVE_UNUSED_CODE_LOCAL_VARIABLES, CleanUpOptions.TRUE);
break;
}
return result;
}
private void qualifyMemberName(SimpleName memberName) {
if (isStaticAccess(memberName)) {
IBinding memberBinding= memberName.resolveBinding();
if (memberBinding instanceof IVariableBinding || memberBinding instanceof IMethodBinding) {
if (fStaticImportsInReference.contains(fNewLocation)) { // use static import if reference location used static import
importStatically(memberName, memberBinding);
return;
} else if (fStaticImportsInInitializer2.contains(memberName)) { // use static import if already imported statically in initializer
importStatically(memberName, memberBinding);
return;
}
}
qualifyToTopLevelClass(memberName); //otherwise: qualify and import non-static
}
}
private static boolean addGetterSetterProposal(IInvocationContext context, ASTNode coveringNode, Collection<ICommandAccess> proposals, int relevance) {
if (!(coveringNode instanceof SimpleName)) {
return false;
}
SimpleName sn= (SimpleName) coveringNode;
IBinding binding= sn.resolveBinding();
if (!(binding instanceof IVariableBinding))
return false;
IVariableBinding variableBinding= (IVariableBinding) binding;
if (!variableBinding.isField())
return false;
if (proposals == null)
return true;
ChangeCorrectionProposal proposal= getProposal(context.getCompilationUnit(), sn, variableBinding, relevance);
if (proposal != null)
proposals.add(proposal);
return true;
}
public static ICleanUpFix createCleanUp(CompilationUnit compilationUnit,
boolean addFinalFields, boolean addFinalParameters, boolean addFinalLocals) {
if (!addFinalFields && !addFinalParameters && !addFinalLocals)
return null;
HashMap<IBinding, List<SimpleName>> writtenNames= new HashMap<IBinding, List<SimpleName>>();
WrittenNamesFinder finder= new WrittenNamesFinder(writtenNames);
compilationUnit.accept(finder);
List<ModifierChangeOperation> operations= new ArrayList<ModifierChangeOperation>();
VariableDeclarationFinder visitor= new VariableDeclarationFinder(addFinalFields, addFinalParameters, addFinalLocals, operations, writtenNames);
compilationUnit.accept(visitor);
if (operations.isEmpty())
return null;
return new VariableDeclarationFix(FixMessages.VariableDeclarationFix_add_final_change_name, compilationUnit, operations.toArray(new CompilationUnitRewriteOperation[operations.size()]));
}
@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 static IBinding getBinding(Expression expression) {
if (expression instanceof FieldAccess) {
return ((FieldAccess)expression).resolveFieldBinding();
} else if (expression instanceof Name) {
return ((Name)expression).resolveBinding();
}
return null;
}
public static boolean isEnumCase(ASTNode node) {
if (node instanceof SwitchCase) {
final SwitchCase caze= (SwitchCase) node;
final Expression expression= caze.getExpression();
if (expression instanceof Name) {
final Name name= (Name) expression;
final IBinding binding= name.resolveBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding variableBinding= (IVariableBinding) binding;
return variableBinding.isEnumConstant();
}
}
}
return false;
}
public static IBinding getDeclaration(IBinding binding) {
switch (binding.getKind()) {
case IBinding.TYPE:
return ((ITypeBinding) binding).getTypeDeclaration();
case IBinding.VARIABLE:
return ((IVariableBinding) binding).getVariableDeclaration();
case IBinding.METHOD:
return ((IMethodBinding) binding).getMethodDeclaration();
}
return binding;
}
private Code generateLocalVarAssignCode(Expression expression,
Expression left, Expression right, TestMethod parentMethod) {
Code rightCode = expressionCode(right, parentMethod);
if (rightCode instanceof UnknownCode) {
// ignore left for UnknownCode assignment
return rightCode;
}
if (!(left instanceof SimpleName)) {
return rightCode; // ignore left
}
SimpleName simpleName = (SimpleName) left;
IBinding leftBinding = simpleName.resolveBinding();
if (!(leftBinding instanceof IVariableBinding)) {
return rightCode; // ignore left
}
IVariableBinding varBinding = (IVariableBinding) leftBinding;
if (varBinding.isField() || varBinding.isParameter()) {
// ignore left for field assignment and method argument assignment
// TODO should handle field assignment as VarAssign for Field ??
return rightCode;
}
String classKey = varBinding.getType().getBinaryName();
TestClass subClass = subClassTable.getByKey(classKey);
if (subClass != null && subClass instanceof PageClass) {
// ignore left for page type variable assignment
// since usually page type variable is not used in other TestDoc
return rightCode;
}
LocalVar localVar = generateLocalVarCode(simpleName, varBinding);
VarAssign assign = new VarAssign();
assign.setOriginal(expression.toString().trim());
assign.setVariable(localVar);
assign.setValue(rightCode);
return assign;
}
private boolean hasAddedStaticImport(SimpleName name) {
IBinding binding= name.resolveBinding();
if (binding instanceof IVariableBinding) {
IVariableBinding variable= (IVariableBinding) binding;
return hasAddedStaticImport(variable.getDeclaringClass().getQualifiedName(), variable.getName(), true);
} else if (binding instanceof IMethodBinding) {
IMethodBinding method= (IMethodBinding) binding;
return hasAddedStaticImport(method.getDeclaringClass().getQualifiedName(), method.getName(), false);
}
return false;
}
@Override
public final boolean visit(final SimpleName node) {
Assert.isNotNull(node);
final IBinding binding= node.resolveBinding();
if (binding instanceof ITypeBinding) {
final ITypeBinding type= (ITypeBinding) binding;
if (!fBindings.contains(type.getKey()) && type.isTypeVariable()) {
fResult.add(node);
fStatus.merge(RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.MoveInstanceMethodProcessor_no_type_variables, JavaStatusContext.create(fMethod.getCompilationUnit(), node)));
return false;
}
}
return true;
}
/**
* Returns the image descriptor for a binding with the flags as defined by {@link JavaElementImageProvider}.
* @param binding The binding to get the image for.
* @param imageFlags The image flags as defined in {@link JavaElementImageProvider}.
* @return the image of the binding or null if there is no image
*/
public static ImageDescriptor getBindingImageDescriptor(IBinding binding, int imageFlags) {
ImageDescriptor baseImage= getBaseImageDescriptor(binding, imageFlags);
if (baseImage != null) {
int adornmentFlags= getAdornmentFlags(binding);
Point size= ((imageFlags & JavaElementImageProvider.SMALL_ICONS) != 0) ? JavaElementImageProvider.SMALL_SIZE : JavaElementImageProvider.BIG_SIZE;
return new JavaElementImageDescriptor(baseImage, adornmentFlags, size);
}
return null;
}
@Override
public boolean visit(SimpleName node) {
IBinding binding= node.resolveBinding();
if (binding == null && !status.hasFatalError()) {
// fixes bug #42753
if (!ASTNodes.isLabel(node)) {
status.addFatalError(
RefactoringCoreMessages.InlineMethodRefactoring_SourceAnalyzer_declaration_has_errors,
JavaStatusContext.create(fTypeRoot, fDeclaration));
return false;
}
}
return true;
}
private StandardType createStandardType(String fullyQualifiedName, IJavaProject focus) {
try {
IType javaElementType= focus.findType(fullyQualifiedName);
StandardType result= fStandardTypes.get(javaElementType);
if (result != null)
return result;
ASTParser parser= ASTParser.newParser(ASTProvider.SHARED_AST_LEVEL);
parser.setProject(focus);
IBinding[] bindings= parser.createBindings(new IJavaElement[] {javaElementType} , null);
return createStandardType((ITypeBinding)bindings[0]);
} catch (JavaModelException e) {
// fall through
}
return null;
}
public static UnusedCodeFix createUnusedTypeParameterFix(CompilationUnit compilationUnit, IProblemLocation problemLoc) {
if (problemLoc.getProblemId() == IProblem.UnusedTypeParameter) {
SimpleName name= getUnusedName(compilationUnit, problemLoc);
if (name != null) {
IBinding binding= name.resolveBinding();
if (binding != null) {
String label= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
RemoveUnusedTypeParameterOperation operation= new RemoveUnusedTypeParameterOperation(name);
return new UnusedCodeFix(label, compilationUnit, new CompilationUnitRewriteOperation[] { operation }, getCleanUpOptions(binding, false));
}
}
}
return null;
}