下面列出了怎么用org.eclipse.jdt.core.dom.ITypeBinding的API类实例代码及写法,或者点击链接到github查看源代码。
public static ICompilationUnit findCompilationUnit(ITypeBinding typeBinding, IJavaProject project) throws JavaModelException {
if (!typeBinding.isFromSource()) {
return null;
}
while (typeBinding != null && !typeBinding.isTopLevel()) {
typeBinding= typeBinding.getDeclaringClass();
}
if (typeBinding != null) {
IPackageBinding pack= typeBinding.getPackage();
String packageName= pack.isUnnamed() ? "" : pack.getName(); //$NON-NLS-1$
IType type= project.findType(packageName, typeBinding.getName());
if (type != null) {
return type.getCompilationUnit();
}
}
return null;
}
private void initializeDestinations() {
List<ASTNode> result= new ArrayList<ASTNode>();
BodyDeclaration decl= fAnalyzer.getEnclosingBodyDeclaration();
ASTNode current= ASTResolving.findParentType(decl.getParent());
if (fAnalyzer.isValidDestination(current)) {
result.add(current);
}
if (current != null && (decl instanceof MethodDeclaration || decl instanceof Initializer || decl instanceof FieldDeclaration)) {
ITypeBinding binding= ASTNodes.getEnclosingType(current);
ASTNode next= ASTResolving.findParentType(current.getParent());
while (next != null && binding != null && binding.isNested()) {
if (fAnalyzer.isValidDestination(next)) {
result.add(next);
}
current= next;
binding= ASTNodes.getEnclosingType(current);
next= ASTResolving.findParentType(next.getParent());
}
}
fDestinations= result.toArray(new ASTNode[result.size()]);
fDestination= fDestinations[fDestinationIndex];
}
public static void getInvalidQualificationProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
ASTNode node= problem.getCoveringNode(context.getASTRoot());
if (!(node instanceof Name)) {
return;
}
Name name= (Name) node;
IBinding binding= name.resolveBinding();
if (!(binding instanceof ITypeBinding)) {
return;
}
ITypeBinding typeBinding= (ITypeBinding)binding;
AST ast= node.getAST();
ASTRewrite rewrite= ASTRewrite.create(ast);
rewrite.replace(name, ast.newName(typeBinding.getQualifiedName()), null);
String label= CorrectionMessages.JavadocTagsSubProcessor_qualifylinktoinner_description;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.QUALIFY_INNER_TYPE_NAME, image);
proposals.add(proposal);
}
/**
* This method initializes all variables used in the process of generating <code>toString</code>
* method.
*/
protected void initialize() {
needMaxLenVariable= false;
needCollectionToStringMethod= false;
typesThatNeedArrayToStringMethod= new ArrayList<ITypeBinding>();
checkNeedForHelperMethods();
toStringMethod= fAst.newMethodDeclaration();
toStringMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PUBLIC));
toStringMethod.setName(fAst.newSimpleName(METHODNAME_TO_STRING));
toStringMethod.setConstructor(false);
toStringMethod.setReturnType2(fAst.newSimpleType(fAst.newName(TYPENAME_STRING)));
Block body= fAst.newBlock();
toStringMethod.setBody(body);
fMaxLenVariableName= createNameSuggestion(MAX_LEN_VARIABLE_NAME, NamingConventions.VK_LOCAL);
}
private Type getNewType(ASTRewrite rewrite) {
AST ast= rewrite.getAST();
Type newTypeNode= null;
ITypeBinding binding= null;
if (fInvocationNode.getLocationInParent() == MemberValuePair.NAME_PROPERTY) {
Expression value= ((MemberValuePair) fInvocationNode.getParent()).getValue();
binding= value.resolveTypeBinding();
} else if (fInvocationNode instanceof Expression) {
binding= ((Expression) fInvocationNode).resolveTypeBinding();
}
if (binding != null) {
ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(fInvocationNode, getImportRewrite());
newTypeNode= getImportRewrite().addImport(binding, ast, importRewriteContext);
}
if (newTypeNode == null) {
newTypeNode= ast.newSimpleType(ast.newSimpleName("String")); //$NON-NLS-1$
}
return newTypeNode;
}
/**
* We pass the signature because we want to get it from the node, but there can
* be different types of nodes (funny JDT).
*/
public Invocation createInvocationFromMethodBinding(IMethodBinding binding, String signature) {
Invocation invocation = new Invocation();
if (topOfContainerStack() instanceof Method)
invocation.setSender((Method) topOfContainerStack());
if (binding != null && binding.getMethodDeclaration() != null) {
IMethodBinding methodDeclarationBinding = binding.getMethodDeclaration();
ITypeBinding declaringClass = null;
if (methodDeclarationBinding.getDeclaringClass() != null)
declaringClass = methodDeclarationBinding.getDeclaringClass();
else
declaringClass = binding.getDeclaringClass();
Type ensureTypeFromTypeBinding = ensureTypeFromTypeBinding(declaringClass);
invocation
.addCandidates(ensureMethodFromMethodBinding(methodDeclarationBinding, ensureTypeFromTypeBinding));
}
invocation.setSignature(signature);
repository.add(invocation);
return invocation;
}
private static ImageDescriptor getTypeImageDescriptor(boolean inner, ITypeBinding binding, int flags) {
if (binding.isEnum())
return JavaPluginImages.DESC_OBJS_ENUM;
else if (binding.isAnnotation())
return JavaPluginImages.DESC_OBJS_ANNOTATION;
else if (binding.isInterface()) {
if ((flags & JavaElementImageProvider.LIGHT_TYPE_ICONS) != 0)
return JavaPluginImages.DESC_OBJS_INTERFACEALT;
if (inner)
return getInnerInterfaceImageDescriptor(binding.getModifiers());
return getInterfaceImageDescriptor(binding.getModifiers());
} else if (binding.isClass()) {
if ((flags & JavaElementImageProvider.LIGHT_TYPE_ICONS) != 0)
return JavaPluginImages.DESC_OBJS_CLASSALT;
if (inner)
return getInnerClassImageDescriptor(binding.getModifiers());
return getClassImageDescriptor(binding.getModifiers());
} else if (binding.isTypeVariable()) {
return JavaPluginImages.DESC_OBJS_TYPEVARIABLE;
}
// primitive type, wildcard
return null;
}
private void addTypeQualification(final Type type, final CompilationUnitRewrite targetRewrite, final TextEditGroup group) {
Assert.isNotNull(type);
Assert.isNotNull(targetRewrite);
final ITypeBinding binding= type.resolveBinding();
if (binding != null) {
final ITypeBinding declaring= binding.getDeclaringClass();
if (declaring != null) {
if (type instanceof SimpleType) {
final SimpleType simpleType= (SimpleType) type;
addSimpleTypeQualification(targetRewrite, declaring, simpleType, group);
} else if (type instanceof ParameterizedType) {
final ParameterizedType parameterizedType= (ParameterizedType) type;
final Type rawType= parameterizedType.getType();
if (rawType instanceof SimpleType)
addSimpleTypeQualification(targetRewrite, declaring, (SimpleType) rawType, group);
}
}
}
}
private static AbstractControlVariable generateConditionControlVariable(Expression dataStructure)
{
// initialize startValue
VariableValue startValue = new VariableValue(0);
// initialize endValue
VariableValue endValue = null;
ITypeBinding dataStructureBinding = dataStructure.resolveTypeBinding();
// if the dataStructure is an array or a mehtodInvocation returning and array (both covered by the first expression) OR
// the data structure is a collection or the data structure is a methodInvocation returning a collection (both covered by the second expression)
// These are the only cases supported by the JAVA enhanced for loop
if (dataStructureBinding.isArray() || AbstractLoopUtilities.isCollection(dataStructureBinding))
{
endValue = new VariableValue(VariableValue.ValueType.DATA_STRUCTURE_SIZE);
}
// initialize variableUpdaters
List<VariableUpdater> variableUpdaters = new ArrayList<VariableUpdater>();
variableUpdaters.add(new VariableUpdater(1));
if (endValue == null)
{
return null;
}
return new AbstractControlVariable(startValue, endValue, variableUpdaters, dataStructure);
}
@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(), null);
}
}
return result;
}
@Override
public boolean visit(TypeDeclaration node) {
AbstractClass clazz = new AbstractClass();
if (node.getSuperclassType() != null) {
ITypeBinding bind = node.getSuperclassType().resolveBinding();
clazz.setSuperClass(bind.getQualifiedName());
}
clazz.setInterface(node.isInterface());
if (packageName != null) {
clazz.setName(packageName+'.'+node.getName().getFullyQualifiedName());
} else {
clazz.setName(node.getName().getFullyQualifiedName());
}
TypeVisitor visitor = new TypeVisitor();
node.accept(visitor);
clazz.setMethods(visitor.getMethods());
clazz.setStartPosition(node.getStartPosition());
clazz.setEndPosition(node.getStartPosition() + node.getLength() - 1);
clazz.setFields(visitor.getFields());
types.add(clazz);
return true;
}
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);
}
}
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel linkedModel) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
IBinding binding= fUnusedName.resolveBinding();
CompilationUnit root= (CompilationUnit) fUnusedName.getRoot();
String displayString= FixMessages.UnusedCodeFix_RemoveUnusedTypeParameter_description;
TextEditGroup group= createTextEditGroup(displayString, cuRewrite);
if (binding.getKind() == IBinding.TYPE) {
ITypeBinding decl= ((ITypeBinding) binding).getTypeDeclaration();
ASTNode declaration= root.findDeclaringNode(decl);
if (declaration.getParent() instanceof TypeDeclarationStatement) {
declaration= declaration.getParent();
}
rewrite.remove(declaration, group);
}
}
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();
}
}
@Override
public final void endVisit(final ArrayInitializer node) {
final ITypeBinding binding= node.resolveTypeBinding();
if (binding != null && binding.isArray()) {
final ConstraintVariable2 ancestor= fModel.createIndependentTypeVariable(binding.getElementType());
if (ancestor != null) {
node.setProperty(PROPERTY_CONSTRAINT_VARIABLE, ancestor);
Expression expression= null;
ConstraintVariable2 descendant= null;
final List<Expression> expressions= node.expressions();
for (int index= 0; index < expressions.size(); index++) {
expression= expressions.get(index);
descendant= (ConstraintVariable2) expression.getProperty(PROPERTY_CONSTRAINT_VARIABLE);
if (descendant != null)
fModel.createSubtypeConstraint(descendant, ancestor);
}
}
}
}
private void addNonPrimitiveParameters(SM_Project parentProject, TypeInfo typeInfo, ITypeBinding iType) {
if (iType.isFromSource() && iType.getModifiers() != 0) {
SM_Type inferredBasicType = findType(iType.getName(), iType.getPackage().getName(), parentProject);
addParameterIfNotAlreadyExists(typeInfo, inferredBasicType);
}
for (ITypeBinding typeParameter : iType.getTypeArguments()) {
if (typeParameter.isParameterizedType()) {
addNonPrimitiveParameters(parentProject, typeInfo, typeParameter);
} else {
if (typeParameter.isFromSource() && typeParameter.getModifiers() != 0) {
SM_Type inferredType = findType(typeParameter.getName(), typeParameter.getPackage().getName(),
parentProject);
if (inferredType != null) {
addParameterIfNotAlreadyExists(typeInfo, inferredType);
}
}
}
}
}
public AccessAnalyzer(SelfEncapsulateFieldRefactoring refactoring, ICompilationUnit unit, IVariableBinding field, ITypeBinding declaringClass, ASTRewrite rewriter, ImportRewrite importRewrite) {
Assert.isNotNull(refactoring);
Assert.isNotNull(unit);
Assert.isNotNull(field);
Assert.isNotNull(declaringClass);
Assert.isNotNull(rewriter);
Assert.isNotNull(importRewrite);
fCUnit= unit;
fFieldBinding= field.getVariableDeclaration();
fDeclaringClassBinding= declaringClass;
fRewriter= rewriter;
fImportRewriter= importRewrite;
fGroupDescriptions= new ArrayList<TextEditGroup>();
fGetter= refactoring.getGetterName();
fSetter= refactoring.getSetterName();
fEncapsulateDeclaringClass= refactoring.getEncapsulateDeclaringClass();
try {
fIsFieldFinal= Flags.isFinal(refactoring.getField().getFlags());
} catch (JavaModelException e) {
// assume non final field
}
fStatus= new RefactoringStatus();
}
public static String getMethodSignature(String name, ITypeBinding[] params, boolean isVarArgs) {
StringBuffer buf= new StringBuffer();
buf.append(name).append('(');
for (int i= 0; i < params.length; i++) {
if (i > 0) {
buf.append(JavaElementLabels.COMMA_STRING);
}
if (isVarArgs && i == params.length - 1) {
buf.append(getTypeSignature(params[i].getElementType()));
buf.append("..."); //$NON-NLS-1$
} else {
buf.append(getTypeSignature(params[i]));
}
}
buf.append(')');
return BasicElementLabels.getJavaElementName(buf.toString());
}
private void qualifyThisExpressions(ASTNode node, final ASTRewrite rewrite, final ImportRewrite importRewrite, final ImportRewriteContext importRewriteContext) {
node.accept(new GenericVisitor() {
/**
* {@inheritDoc}
*/
@Override
public boolean visit(ThisExpression thisExpr) {
if (thisExpr.getQualifier() == null) {
ITypeBinding typeBinding= thisExpr.resolveTypeBinding();
if (typeBinding != null) {
String typeName= importRewrite.addImport(typeBinding.getTypeDeclaration(), importRewriteContext);
SimpleName simpleName= thisExpr.getAST().newSimpleName(typeName);
rewrite.set(thisExpr, ThisExpression.QUALIFIER_PROPERTY, simpleName, null);
}
}
return super.visit(thisExpr);
}
});
}
private static boolean isVariableDefinedInContext(IBinding binding, ITypeBinding typeVariable) {
if (binding.getKind() == IBinding.VARIABLE) {
IVariableBinding var= (IVariableBinding) binding;
binding= var.getDeclaringMethod();
if (binding == null) {
binding= var.getDeclaringClass();
}
}
if (binding instanceof IMethodBinding) {
if (binding == typeVariable.getDeclaringMethod()) {
return true;
}
binding= ((IMethodBinding) binding).getDeclaringClass();
}
while (binding instanceof ITypeBinding) {
if (binding == typeVariable.getDeclaringClass()) {
return true;
}
if (Modifier.isStatic(binding.getModifiers())) {
break;
}
binding= ((ITypeBinding) binding).getDeclaringClass();
}
return false;
}
private static ASTRewriteCorrectionProposal createNoSideEffectProposal(IInvocationContext context, SimpleName nodeToQualify, IVariableBinding fieldBinding, String label, int relevance) {
AST ast= nodeToQualify.getAST();
Expression qualifier;
if (Modifier.isStatic(fieldBinding.getModifiers())) {
ITypeBinding declaringClass= fieldBinding.getDeclaringClass();
qualifier= ast.newSimpleName(declaringClass.getTypeDeclaration().getName());
} else {
qualifier= ast.newThisExpression();
}
ASTRewrite rewrite= ASTRewrite.create(ast);
FieldAccess access= ast.newFieldAccess();
access.setName((SimpleName) rewrite.createCopyTarget(nodeToQualify));
access.setExpression(qualifier);
rewrite.replace(nodeToQualify, access, null);
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
return new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, relevance, image);
}
private static List<IMethodBinding> computeOverridableMethodsForInterface(
ITypeBinding interfaceBinding) {
assert (interfaceBinding.isInterface());
List<ITypeBinding> superInterfaces = new ArrayList<ITypeBinding>();
RemoteServiceUtilities.expandSuperInterfaces(interfaceBinding,
superInterfaces);
List<IMethodBinding> overridableMethods = new ArrayList<IMethodBinding>();
for (ITypeBinding superInterface : superInterfaces) {
for (IMethodBinding declaredMethod : superInterface.getDeclaredMethods()) {
if (findOverridingMethod(declaredMethod, overridableMethods) == null) {
overridableMethods.add(declaredMethod);
}
}
}
return overridableMethods;
}
public SM_Type resolveType(Type type, SM_Project project) {
ITypeBinding binding = type.resolveBinding();
if (binding == null || binding.getPackage() == null) // instanceof String[] returns null package
return null;
SM_Package pkg = findPackage(binding.getPackage().getName(), project);
if (pkg != null) {
return findType(binding.getName(), pkg);
}
return null;
}
private static void getTypeParametersLabel(ITypeBinding[] typeParameters, StringBuffer buffer) {
if (typeParameters.length > 0) {
buffer.append('<');
for (int index= 0; index < typeParameters.length; index++) {
if (index > 0) {
buffer.append(JavaElementLabels.COMMA_STRING);
}
buffer.append(typeParameters[index].getName());
}
buffer.append('>');
}
}
private static ParameterizedType createQualifiedParameterizedType(AST ast, ITypeBinding typeBinding, ASTRewrite rewriter) {
ITypeBinding erasure = typeBinding.getErasure();
ITypeBinding[] typeArguments = typeBinding.getTypeArguments();
ParameterizedType parameterizedType = ast.newParameterizedType(generateQualifiedTypeFromTypeBinding(erasure, ast, rewriter));
ListRewrite typeArgumentsRewrite = rewriter.getListRewrite(parameterizedType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
for(ITypeBinding typeArgument : typeArguments) {
typeArgumentsRewrite.insertLast(generateQualifiedTypeFromTypeBinding(typeArgument, ast, rewriter), null);
}
return parameterizedType;
}
public static ITypeBinding obtainTypeBindingFromExpression(Expression expr) {
if(expr instanceof TypeLiteral) {
return ((TypeLiteral) expr).getType().resolveBinding();
}
return null;
}
public void checkInput(RefactoringStatus status, String methodName, ASTNode destination) {
ITypeBinding[] arguments= getArgumentTypes();
ITypeBinding type= ASTNodes.getEnclosingType(destination);
status.merge(Checks.checkMethodInType(type, methodName, arguments));
ITypeBinding superClass= type.getSuperclass();
if (superClass != null) {
status.merge(Checks.checkMethodInHierarchy(superClass, methodName, null, arguments));
}
for (ITypeBinding superInterface : type.getInterfaces()) {
status.merge(Checks.checkMethodInHierarchy(superInterface, methodName, null, arguments));
}
}
private ASTNode getNewQualifiedNameNode(ITypeBinding[] parameters, Name name) {
final AST ast= name.getAST();
boolean raw= false;
final ITypeBinding binding= name.resolveTypeBinding();
if (binding != null && binding.isRawType())
raw= true;
if (parameters != null && parameters.length > 0 && !raw) {
final ParameterizedType type= ast.newParameterizedType(ast.newSimpleType(ast.newName(fQualifiedTypeName)));
for (int index= 0; index < parameters.length; index++)
type.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
return type;
}
return ast.newName(fQualifiedTypeName);
}
private static boolean isInterfaceOrAnnotationMember(IBinding binding) {
ITypeBinding declaringType= null;
if (binding instanceof IVariableBinding) {
declaringType= ((IVariableBinding) binding).getDeclaringClass();
} else if (binding instanceof IMethodBinding) {
declaringType= ((IMethodBinding) binding).getDeclaringClass();
} else if (binding instanceof ITypeBinding) {
declaringType= ((ITypeBinding) binding).getDeclaringClass();
}
return declaringType != null && (declaringType.isInterface() || declaringType.isAnnotation());
}
private String getSignature(IMethodBinding binding) {
StringBuffer buf= new StringBuffer(binding.getName()).append('(');
ITypeBinding[] parameterTypes= binding.getParameterTypes();
for (int i= 0; i < parameterTypes.length; i++) {
buf.append(parameterTypes[i].getTypeDeclaration().getName());
}
buf.append(')');
return buf.toString();
}