下面列出了org.eclipse.jdt.core.dom.SuperMethodReference#org.eclipse.jdt.core.dom.ParameterizedType 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Object provideAnswer(InvocationOnMock inv) {
Type type = ((BuilderField) inv.getArguments()[0]).getFieldType();
if (type instanceof ParameterizedType) {
Type baseType = ((ParameterizedType) type).getType();
if (baseType instanceof SimpleType) {
String name = ((SimpleType) baseType).getName().getFullyQualifiedName();
// if name is fully qualified
if (recognisedClasses.contains(name)) {
return Optional.ofNullable(name);
}
Optional<String> found = recognisedClasses.stream()
.filter(fqn -> fqn.endsWith("." + name))
.findFirst();
if (found.isPresent()) {
return found;
}
}
}
return Optional.of("some.other.value");
}
@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) {
return false;
}
// 2: match type arguments
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
if (locationInParent == ParameterizedType.TYPE_ARGUMENTS_PROPERTY) {
return true;
}
return false;
}
public boolean visit(ParameterizedType type) {
/*
* ParameterizedType: Type < Type { , Type } >
*/
activateDiffStyle(type);
handleType(type.getType());
appendOpenBrace();
for (int i = 0; i < type.typeArguments().size(); i++) {
handleType((Type) type.typeArguments().get(i));
if (i < type.typeArguments().size() - 1) {
appendComma();
}
}
appendClosedBrace();
deactivateDiffStyle(type);
return false;
}
private void addTypeParameters(TypeDeclaration newDeclaration) {
if (isParameterizedType(fTypeKind, fNode)) {
String typeArgBaseName = getGenericTypeArgBaseName(ASTNodes.getSimpleNameIdentifier(fNode));
int nTypeArgs = ((ParameterizedType) fNode.getParent().getParent()).typeArguments().size();
String[] typeArgNames = new String[nTypeArgs];
if (nTypeArgs == 1) {
typeArgNames[0] = typeArgBaseName;
} else {
for (int i = 0; i < nTypeArgs; i++) {
StringBuilder buf = new StringBuilder(typeArgBaseName);
buf.append(i + 1);
typeArgNames[i] = buf.toString();
}
}
AST ast = newDeclaration.getAST();
for (String typeArgName : typeArgNames) {
TypeParameter typeArg = ast.newTypeParameter();
typeArg.setName(ast.newSimpleName(typeArgName));
newDeclaration.typeParameters().add(typeArg);
}
}
}
private ParameterizedType createPrivilegedActionType(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
Name privilegedActionName;
if (isUpdateImports()) {
privilegedActionName = ast.newSimpleName(PrivilegedAction.class.getSimpleName());
} else {
privilegedActionName = ast.newName(PrivilegedAction.class.getName());
}
SimpleType rawPrivilegedActionType = ast.newSimpleType(privilegedActionName);
ParameterizedType privilegedActionType = ast.newParameterizedType(rawPrivilegedActionType);
Type typeArgument = (Type) rewrite.createCopyTarget(classLoaderCreation.getType());
List<Type> typeArguments = checkedList(privilegedActionType.typeArguments());
typeArguments.add(typeArgument);
return privilegedActionType;
}
/**
* @param type
* @return
*/
private String getParametrizedType(final ParameterizedType type, final Boolean innerTypes) {
final StringBuilder sb = new StringBuilder(getFullyQualifiedNameFor(type
.getType().toString()));
if(innerTypes) {
sb.append("<");
for (final Object typeArg : type.typeArguments()) {
final Type arg = (Type) typeArg;
final String argString = getNameOfType(arg);
sb.append(argString);
sb.append(",");
}
sb.deleteCharAt(sb.length() - 1);
sb.append(">");
}
return sb.toString();
}
@SuppressWarnings("unchecked")
private static ITypeBinding getOwnerTypeBinding(
TypeDeclaration uiBinderSubtype) {
List<Type> superInterfaces = uiBinderSubtype.superInterfaceTypes();
for (Type superInterface : superInterfaces) {
ITypeBinding binding = superInterface.resolveBinding();
if (binding != null) {
if (binding.getErasure().getQualifiedName().equals(
UiBinderConstants.UI_BINDER_TYPE_NAME)) {
if (superInterface instanceof ParameterizedType) {
ParameterizedType uiBinderType = (ParameterizedType) superInterface;
List<Type> typeArgs = uiBinderType.typeArguments();
if (typeArgs.size() == 2) {
Type ownerType = typeArgs.get(1);
return ownerType.resolveBinding();
}
}
}
}
}
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 void updateCu(CompilationUnit unit, Set<ConstraintVariable> vars, CompilationUnitChange unitChange,
ASTRewrite unitRewriter, String typeName) throws JavaModelException {
// use custom SourceRangeComputer to avoid losing comments
unitRewriter.setTargetSourceRangeComputer(new SourceRangeComputer());
for (Iterator<ConstraintVariable> it=vars.iterator(); it.hasNext(); ){
ConstraintVariable cv = it.next();
ASTNode decl= findDeclaration(unit, cv);
if ((decl instanceof SimpleName || decl instanceof QualifiedName) && cv instanceof ExpressionVariable) {
ASTNode gp= decl.getParent().getParent();
updateType(unit, getType(gp), unitChange, unitRewriter, typeName); // local variable or parameter
} else if (decl instanceof MethodDeclaration || decl instanceof FieldDeclaration) {
updateType(unit, getType(decl), unitChange, unitRewriter, typeName); // method return or field type
} else if (decl instanceof ParameterizedType){
updateType(unit, getType(decl), unitChange, unitRewriter, typeName);
}
}
}
/**
* Creates the appropriate ParameterizedType node. Recursion is needed to
* handle the nested case (e.g., Vector<Vector<String>>).
* @param ast
* @param typeBinding
* @return the created type
*/
private Type createParameterizedType(AST ast, ITypeBinding typeBinding){
if (typeBinding.isParameterizedType() && !typeBinding.isRawType()){
Type baseType= ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
ParameterizedType newType= ast.newParameterizedType(baseType);
for (int i=0; i < typeBinding.getTypeArguments().length; i++){
ITypeBinding typeArg= typeBinding.getTypeArguments()[i];
Type argType= createParameterizedType(ast, typeArg); // recursive call
newType.typeArguments().add(argType);
}
return newType;
} else {
if (!typeBinding.isTypeVariable()){
return ast.newSimpleType(ASTNodeFactory.newName(ast, typeBinding.getErasure().getName()));
} else {
return ast.newSimpleType(ast.newSimpleName(typeBinding.getName()));
}
}
}
private static Type getType(ASTNode node) {
switch(node.getNodeType()){
case ASTNode.SINGLE_VARIABLE_DECLARATION:
return ((SingleVariableDeclaration) node).getType();
case ASTNode.FIELD_DECLARATION:
return ((FieldDeclaration) node).getType();
case ASTNode.VARIABLE_DECLARATION_STATEMENT:
return ((VariableDeclarationStatement) node).getType();
case ASTNode.VARIABLE_DECLARATION_EXPRESSION:
return ((VariableDeclarationExpression) node).getType();
case ASTNode.METHOD_DECLARATION:
return ((MethodDeclaration)node).getReturnType2();
case ASTNode.PARAMETERIZED_TYPE:
return ((ParameterizedType)node).getType();
default:
Assert.isTrue(false);
return null;
}
}
/**
* The selection corresponds to a ParameterizedType (return type of method)
* @param pt the type
* @return the message
*/
private String parameterizedTypeSelected(ParameterizedType pt) {
ASTNode parent= pt.getParent();
if (parent.getNodeType() == ASTNode.METHOD_DECLARATION){
fMethodBinding= ((MethodDeclaration)parent).resolveBinding();
fParamIndex= -1;
fEffectiveSelectionStart= pt.getStartPosition();
fEffectiveSelectionLength= pt.getLength();
setOriginalType(pt.resolveBinding());
} else if (parent.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION){
return singleVariableDeclarationSelected((SingleVariableDeclaration)parent);
} else if (parent.getNodeType() == ASTNode.VARIABLE_DECLARATION_STATEMENT){
return variableDeclarationStatementSelected((VariableDeclarationStatement)parent);
} else if (parent.getNodeType() == ASTNode.FIELD_DECLARATION){
return fieldDeclarationSelected((FieldDeclaration)parent);
} else {
return nodeTypeNotSupported();
}
return null;
}
public static ParameterizedType[] inferArguments(SimpleType[] types, InferTypeArgumentsUpdate update, InferTypeArgumentsTCModel model, CompilationUnitRewrite rewrite) {
for (int i= 0; i < types.length; i++) {
types[i].setProperty(REWRITTEN, null);
}
List<ParameterizedType> result= new ArrayList<ParameterizedType>();
HashMap<ICompilationUnit, CuUpdate> updates= update.getUpdates();
Set<Entry<ICompilationUnit, CuUpdate>> entrySet= updates.entrySet();
for (Iterator<Entry<ICompilationUnit, CuUpdate>> iter= entrySet.iterator(); iter.hasNext();) {
Entry<ICompilationUnit, CuUpdate> entry= iter.next();
rewrite.setResolveBindings(false);
CuUpdate cuUpdate= entry.getValue();
for (Iterator<CollectionElementVariable2> cvIter= cuUpdate.getDeclarations().iterator(); cvIter.hasNext();) {
ConstraintVariable2 cv= cvIter.next();
ParameterizedType newNode= rewriteConstraintVariable(cv, rewrite, model, false, types);
if (newNode != null)
result.add(newNode);
}
}
return result.toArray(new ParameterizedType[result.size()]);
}
private ASTNode createNewClassInstanceCreation(CompilationUnitRewrite rewrite, ITypeBinding[] parameters) {
AST ast= fAnonymousInnerClassNode.getAST();
ClassInstanceCreation newClassCreation= ast.newClassInstanceCreation();
newClassCreation.setAnonymousClassDeclaration(null);
Type type= null;
SimpleName newNameNode= ast.newSimpleName(fClassName);
if (parameters.length > 0) {
final ParameterizedType parameterized= ast.newParameterizedType(ast.newSimpleType(newNameNode));
for (int index= 0; index < parameters.length; index++)
parameterized.typeArguments().add(ast.newSimpleType(ast.newSimpleName(parameters[index].getName())));
type= parameterized;
} else
type= ast.newSimpleType(newNameNode);
newClassCreation.setType(type);
copyArguments(rewrite, newClassCreation);
addArgumentsForLocalsUsedInInnerClass(newClassCreation);
addLinkedPosition(KEY_TYPE_NAME, newNameNode, rewrite.getASTRewrite(), true);
return newClassCreation;
}
/**
* Sets the type being instantiated in the given constructor call, including
* specifying any necessary type arguments.
* @param newCtorCall the constructor call to modify
* @param ctorTypeName the simple name of the type being instantiated
* @param ctorOwnerTypeParameters the formal type parameters of the type being
* instantiated
* @param ast utility object used to create AST nodes
*/
private void setCtorTypeArguments(ClassInstanceCreation newCtorCall, String ctorTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
if (ctorOwnerTypeParameters.length == 0) // easy, just a simple type
newCtorCall.setType(ASTNodeFactory.newType(ast, ctorTypeName));
else {
Type baseType= ast.newSimpleType(ast.newSimpleName(ctorTypeName));
ParameterizedType newInstantiatedType= ast.newParameterizedType(baseType);
List<Type> newInstTypeArgs= newInstantiatedType.typeArguments();
for(int i= 0; i < ctorOwnerTypeParameters.length; i++) {
Type typeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName());
newInstTypeArgs.add(typeArg);
}
newCtorCall.setType(newInstantiatedType);
}
}
/**
* Sets the return type of the factory method, including any necessary type
* arguments. E.g., for constructor <code>Foo()</code> in <code>Foo<T></code>,
* the factory method defines a method type parameter <code><T></code> and
* returns a <code>Foo<T></code>.
* @param newMethod the method whose return type is to be set
* @param retTypeName the simple name of the return type (without type parameters)
* @param ctorOwnerTypeParameters the formal type parameters of the type that the
* factory method instantiates (whose constructor is being encapsulated)
* @param ast utility object used to create AST nodes
*/
private void setMethodReturnType(MethodDeclaration newMethod, String retTypeName, ITypeBinding[] ctorOwnerTypeParameters, AST ast) {
if (ctorOwnerTypeParameters.length == 0)
newMethod.setReturnType2(ast.newSimpleType(ast.newSimpleName(retTypeName)));
else {
Type baseType= ast.newSimpleType(ast.newSimpleName(retTypeName));
ParameterizedType newRetType= ast.newParameterizedType(baseType);
List<Type> newRetTypeArgs= newRetType.typeArguments();
for(int i= 0; i < ctorOwnerTypeParameters.length; i++) {
Type retTypeArg= ASTNodeFactory.newType(ast, ctorOwnerTypeParameters[i].getName());
newRetTypeArgs.add(retTypeArg);
}
newMethod.setReturnType2(newRetType);
}
}
/**
* For {@link Name} or {@link Type} nodes, returns the topmost {@link Type} node
* that shares the same type binding as the given node.
*
* @param node an ASTNode
* @return the normalized {@link Type} node or the original node
*/
public static ASTNode getNormalizedNode(ASTNode node) {
ASTNode current= node;
// normalize name
if (QualifiedName.NAME_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
// normalize type
if (QualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())
|| SimpleType.NAME_PROPERTY.equals(current.getLocationInParent())
|| NameQualifiedType.NAME_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
// normalize parameterized types
if (ParameterizedType.TYPE_PROPERTY.equals(current.getLocationInParent())) {
current= current.getParent();
}
return current;
}
private static String[] getVariableNameSuggestions(int variableKind, IJavaProject project, Type expectedType, Collection<String> excluded, boolean evaluateDefault) {
int dim= 0;
if (expectedType.isArrayType()) {
ArrayType arrayType= (ArrayType)expectedType;
dim= arrayType.getDimensions();
expectedType= arrayType.getElementType();
}
if (expectedType.isParameterizedType()) {
expectedType= ((ParameterizedType)expectedType).getType();
}
String typeName= ASTNodes.getTypeName(expectedType);
if (typeName.length() > 0) {
return getVariableNameSuggestions(variableKind, project, typeName, dim, excluded, evaluateDefault);
}
return EMPTY;
}
/**
* Returns the declaration node for the originally selected node.
* @param name the name of the node
*
* @return the declaration node
*/
private static ASTNode getDeclarationNode(SimpleName name) {
ASTNode parent= name.getParent();
if (!(parent instanceof AbstractTypeDeclaration)) {
parent= parent.getParent();
if (parent instanceof ParameterizedType || parent instanceof Type)
parent= parent.getParent();
if (parent instanceof ClassInstanceCreation) {
final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
parent= creation.getAnonymousClassDeclaration();
}
}
return parent;
}
/**
* {@inheritDoc}
*/
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
TextEditGroup group= createTextEditGroup(FixMessages.TypeParametersFix_insert_inferred_type_arguments_description, cuRewrite);
ASTRewrite rewrite= cuRewrite.getASTRewrite();
ImportRewrite importRewrite= cuRewrite.getImportRewrite();
AST ast= cuRewrite.getRoot().getAST();
for (int i= 0; i < fCreatedTypes.length; i++) {
ParameterizedType createdType= fCreatedTypes[i];
ITypeBinding[] typeArguments= createdType.resolveBinding().getTypeArguments();
ContextSensitiveImportRewriteContext importContext= new ContextSensitiveImportRewriteContext(cuRewrite.getRoot(), createdType.getStartPosition(), importRewrite);
ListRewrite argumentsRewrite= rewrite.getListRewrite(createdType, ParameterizedType.TYPE_ARGUMENTS_PROPERTY);
for (int j= 0; j < typeArguments.length; j++) {
ITypeBinding typeArgument= typeArguments[j];
Type argumentNode= importRewrite.addImport(typeArgument, ast, importContext);
argumentsRewrite.insertLast(argumentNode, group);
}
}
}
/**
* Hook method that gets called when the list of super interface has changed. The method
* validates the super interfaces and returns the status of the validation.
* <p>
* Subclasses may extend this method to perform their own validation.
* </p>
*
* @return the status of the validation
*/
protected IStatus superInterfacesChanged() {
StatusInfo status= new StatusInfo();
IPackageFragmentRoot root= getPackageFragmentRoot();
fSuperInterfacesDialogField.enableButton(0, root != null);
if (root != null) {
List<InterfaceWrapper> elements= fSuperInterfacesDialogField.getElements();
int nElements= elements.size();
for (int i= 0; i < nElements; i++) {
String intfname= elements.get(i).interfaceName;
Type type= TypeContextChecker.parseSuperInterface(intfname);
if (type == null) {
status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_InvalidSuperInterfaceName, BasicElementLabels.getJavaElementName(intfname)));
return status;
}
if (type instanceof ParameterizedType && ! JavaModelUtil.is50OrHigher(root.getJavaProject())) {
status.setError(Messages.format(NewWizardMessages.NewTypeWizardPage_error_SuperInterfaceNotParameterized, BasicElementLabels.getJavaElementName(intfname)));
return status;
}
}
}
return status;
}
@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)
return false;
// 2: match type arguments
StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
if (locationInParent == ParameterizedType.TYPE_ARGUMENTS_PROPERTY)
return true;
return false;
}
public static void removeMismatchedArguments(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals){
ICompilationUnit cu= context.getCompilationUnit();
ASTNode selectedNode= problem.getCoveredNode(context.getASTRoot());
if (!(selectedNode instanceof SimpleName)) {
return;
}
ASTNode normalizedNode=ASTNodes.getNormalizedNode(selectedNode);
if (normalizedNode instanceof ParameterizedType) {
ASTRewrite rewrite = ASTRewrite.create(normalizedNode.getAST());
ParameterizedType pt = (ParameterizedType) normalizedNode;
ASTNode mt = rewrite.createMoveTarget(pt.getType());
rewrite.replace(pt, mt, null);
String label= CorrectionMessages.TypeArgumentMismatchSubProcessor_removeTypeArguments;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.REMOVE_TYPE_ARGUMENTS, image);
proposals.add(proposal);
}
}
private static String getTypeName(int typeKind, Name node) {
String name= ASTNodes.getSimpleNameIdentifier(node);
if (typeKind == K_CLASS || typeKind == K_INTERFACE) {
ASTNode parent= node.getParent();
if (parent.getLocationInParent() == ParameterizedType.TYPE_PROPERTY) {
String typeArgBaseName= name.startsWith(String.valueOf('T')) ? String.valueOf('S') : String.valueOf('T'); // use 'S' or 'T'
int nTypeArgs= ((ParameterizedType) parent.getParent()).typeArguments().size();
StringBuffer buf= new StringBuffer(name);
buf.append('<');
if (nTypeArgs == 1) {
buf.append(typeArgBaseName);
} else {
for (int i= 0; i < nTypeArgs; i++) {
if (i != 0)
buf.append(", "); //$NON-NLS-1$
buf.append(typeArgBaseName).append(i + 1);
}
}
buf.append('>');
return buf.toString();
}
}
return name;
}
public boolean visit(AnonymousClassDeclaration node) {
ASTNode name;
ASTNode parent = node.getParent();
switch (parent.getNodeType()) {
case ASTNode.CLASS_INSTANCE_CREATION:
name = ((ClassInstanceCreation) parent).getType();
if (name.getNodeType() == ASTNode.PARAMETERIZED_TYPE) {
name = ((ParameterizedType) name).getType();
}
break;
case ASTNode.ENUM_CONSTANT_DECLARATION:
name = ((EnumConstantDeclaration) parent).getName();
break;
default:
return true;
}
if (found(node, name) && this.resolveBinding)
this.foundBinding = node.resolveBinding();
return true;
}
/**
* @return a String representation of 'type'. Handles qualified, simple and parameterized types.
*/
@Nullable
private String getNameOfType(Type type) {
if (type instanceof QualifiedType) {
return extractTypeNameWithoutGenerics((QualifiedType) type);
}
if (type instanceof SimpleType) {
return ((SimpleType) type).getName().getFullyQualifiedName();
}
if (type instanceof ParameterizedType) {
return getNameOfType(((ParameterizedType) type).getType());
}
return null;
}
@Test
public void testExtractTypeNameWithoutGenerics() {
AST ast = AST.newAST(AST.JLS4);
org.eclipse.jdt.core.dom.SimpleName entry = ast.newSimpleName("Entry");
ParameterizedType map = ast.newParameterizedType(ast.newSimpleType(ast.newSimpleName("Map")));
map.typeArguments().add(ast.newSimpleType(ast.newSimpleName("Foo")));
QualifiedType type = ast.newQualifiedType(map, entry);
assertThat(type.toString()).isEqualTo("Map<Foo>.Entry");
assertThat(ReferencedClassesParser.extractTypeNameWithoutGenerics(type)).isEqualTo("Map.Entry");
}
private void specifyTypes(Type type) {
if (type.isParameterizedType()) {
ParameterizedType parameterizedType = (ParameterizedType) type;
List<Type> typeArgs = parameterizedType.typeArguments();
for (int i = 0; i < typeArgs.size(); i++)
setTypeList(typeArgs.get(i));
} else if (type.isArrayType()) {
Type arrayType = ((ArrayType) type).getElementType();
setArrayType(arrayType);
}
}
@Override
public void endVisit(ParameterizedType node) {
if (skipNode(node)) {
return;
}
GenericSequentialFlowInfo info = processSequential(node, node.getType());
process(info, node.typeArguments());
}
private ClassInstanceCreation createPrivilegedActionCreation(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
ClassInstanceCreation privilegedActionCreation = ast.newClassInstanceCreation();
ParameterizedType privilegedActionType = createPrivilegedActionType(rewrite, classLoaderCreation);
AnonymousClassDeclaration anonymousClassDeclaration = createAnonymousClassDeclaration(rewrite, classLoaderCreation);
privilegedActionCreation.setType(privilegedActionType);
privilegedActionCreation.setAnonymousClassDeclaration(anonymousClassDeclaration);
return privilegedActionCreation;
}