org.eclipse.jdt.core.dom.ClassInstanceCreation#getAnonymousClassDeclaration ( )源码实例Demo

下面列出了org.eclipse.jdt.core.dom.ClassInstanceCreation#getAnonymousClassDeclaration ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: RefactoringMiner   文件: ObjectCreation.java
public ObjectCreation(CompilationUnit cu, String filePath, ClassInstanceCreation creation) {
	this.locationInfo = new LocationInfo(cu, filePath, creation, CodeElementType.CLASS_INSTANCE_CREATION);
	this.type = UMLType.extractTypeObject(cu, filePath, creation.getType(), 0);
	this.typeArguments = creation.arguments().size();
	this.arguments = new ArrayList<String>();
	List<Expression> args = creation.arguments();
	for(Expression argument : args) {
		this.arguments.add(argument.toString());
	}
	if(creation.getExpression() != null) {
		this.expression = creation.getExpression().toString();
	}
	if(creation.getAnonymousClassDeclaration() != null) {
		this.anonymousClassDeclaration = creation.getAnonymousClassDeclaration().toString();
	}
}
 
@Override
public void endVisit(ClassInstanceCreation node) {
	Expression receiver= node.getExpression();
	Type createdType= node.getType();

	ConstraintVariable2 typeCv;
	if (node.getAnonymousClassDeclaration() == null) {
		typeCv= getConstraintVariable(createdType);
	} else {
		typeCv= fTCModel.makeImmutableTypeVariable(createdType.resolveBinding(), null);
		setConstraintVariable(createdType, typeCv);
	}
	setConstraintVariable(node, typeCv);

	IMethodBinding methodBinding= node.resolveConstructorBinding();
	Map<String, IndependentTypeVariable2> methodTypeVariables= createMethodTypeArguments(methodBinding);
	List<Expression> arguments= node.arguments();
	doVisitMethodInvocationArguments(methodBinding, arguments, receiver, methodTypeVariables, createdType);
}
 
/**
 * 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;
}
 
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(MethodDeclaration methodDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	List<Expression> classInstanceCreations = expressionExtractor.getClassInstanceCreations(methodDeclaration.getBody());
	for(Expression expression : classInstanceCreations) {
		ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
		AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
		if(anonymousClassDeclaration != null) {
			List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
			for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
				if(bodyDeclaration instanceof MethodDeclaration)
					methods.add((MethodDeclaration)bodyDeclaration);
			}
		}
	}
	return methods;
}
 
private Set<MethodDeclaration> getMethodDeclarationsWithinAnonymousClassDeclarations(FieldDeclaration fieldDeclaration) {
	Set<MethodDeclaration> methods = new LinkedHashSet<MethodDeclaration>();
	List<VariableDeclarationFragment> fragments = fieldDeclaration.fragments();
	for(VariableDeclarationFragment fragment : fragments) {
		Expression expression = fragment.getInitializer();
		if(expression != null && expression instanceof ClassInstanceCreation) {
			ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)expression;
			AnonymousClassDeclaration anonymousClassDeclaration = classInstanceCreation.getAnonymousClassDeclaration();
			if(anonymousClassDeclaration != null) {
				List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
				for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
					if(bodyDeclaration instanceof MethodDeclaration)
						methods.add((MethodDeclaration)bodyDeclaration);
				}
			}
		}
	}
	return methods;
}
 
源代码6 项目: SimFix   文件: CodeBlock.java
private ClassInstanceCreate visit(ClassInstanceCreation node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	ClassInstanceCreate classInstanceCreate = new ClassInstanceCreate(startLine, endLine, node);
	
	if(node.getExpression() != null){
		Expr expression = (Expr) process(node.getExpression());
		expression.setParent(classInstanceCreate);
		classInstanceCreate.setExpression(expression);
	}
	
	if(node.getAnonymousClassDeclaration() != null){
		AnonymousClassDecl anonymousClassDecl = (AnonymousClassDecl) process(node.getAnonymousClassDeclaration());
		anonymousClassDecl.setParent(classInstanceCreate);
		classInstanceCreate.setAnonymousClassDecl(anonymousClassDecl);
	}

	List<Expr> arguments = new ArrayList<>();
	for(Object object : node.arguments()){
		Expr arg = (Expr) process((ASTNode) object);
		arg.setParent(classInstanceCreate);
		arguments.add(arg);
	}
	classInstanceCreate.setArguments(arguments);
	
	classInstanceCreate.setClassType(node.getType());
	classInstanceCreate.setType(node.getType());
	
	return classInstanceCreate;
}
 
源代码7 项目: eclipse.jdt.ls   文件: ASTNodeDeleteUtil.java
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
	// fields are different because you don't delete the whole declaration but only a fragment of it
	if (element.getElementType() == IJavaElement.FIELD) {
		if (JdtFlags.isEnum((IField) element)) {
			return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
		} else {
			return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
		}
	}
	if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
		IType type= (IType) element;
		if (type.isAnonymous()) {
			if (type.getParent().getElementType() == IJavaElement.FIELD) {
				EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
				if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null)  {
					return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
				}
			}
			ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
			if (creation != null) {
				if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
					return new ASTNode[] { creation.getParent() };
				} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
					return new ASTNode[] { creation};
				}
				return new ASTNode[] { creation.getAnonymousClassDeclaration() };
			}
			return new ASTNode[0];
		} else {
			ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
			// we have to delete the TypeDeclarationStatement
			nodes[0]= nodes[0].getParent();
			return nodes;
		}
	}
	return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}
 
源代码8 项目: xtext-xtend   文件: ASTFlattenerUtils.java
public boolean isLambdaCase(final ClassInstanceCreation creation) {
  final AnonymousClassDeclaration anonymousClazz = creation.getAnonymousClassDeclaration();
  if (((anonymousClazz != null) && (anonymousClazz.bodyDeclarations().size() == 1))) {
    final Object declaredMethod = anonymousClazz.bodyDeclarations().get(0);
    if (((declaredMethod instanceof MethodDeclaration) && (creation.getType().resolveBinding() != null))) {
      final IMethodBinding methodBinding = ((MethodDeclaration) declaredMethod).resolveBinding();
      if ((methodBinding != null)) {
        final IMethodBinding overrides = this.findOverride(methodBinding, methodBinding.getDeclaringClass(), true);
        return ((overrides != null) && Modifier.isAbstract(overrides.getModifiers()));
      }
    }
  }
  return false;
}
 
@Override
public final boolean visit(final ClassInstanceCreation node) {
	Assert.isNotNull(node);
	if (node.getParent() instanceof ClassInstanceCreation) {
		final AnonymousClassDeclaration declaration= node.getAnonymousClassDeclaration();
		if (declaration != null)
			visit(declaration);
		return false;
	}
	return super.visit(node);
}
 
@Override
public ITypeConstraint[] create(ClassInstanceCreation instanceCreation){
	List<Expression> arguments= instanceCreation.arguments();
	List<ITypeConstraint> result= new ArrayList<ITypeConstraint>(arguments.size());
	IMethodBinding methodBinding= instanceCreation.resolveConstructorBinding();
	result.addAll(Arrays.asList(getArgumentConstraints(arguments, methodBinding)));
	if (instanceCreation.getAnonymousClassDeclaration() == null){
		ConstraintVariable constructorVar= fConstraintVariableFactory.makeExpressionOrTypeVariable(instanceCreation, getContext());
		ConstraintVariable typeVar= fConstraintVariableFactory.makeRawBindingVariable(instanceCreation.resolveTypeBinding());
		result.addAll(Arrays.asList(fTypeConstraintFactory.createDefinesConstraint(constructorVar, typeVar)));
	}
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
	// fields are different because you don't delete the whole declaration but only a fragment of it
	if (element.getElementType() == IJavaElement.FIELD) {
		if (JdtFlags.isEnum((IField) element))
			return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
		else
			return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
	}
	if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
		IType type= (IType) element;
		if (type.isAnonymous()) {
			if (type.getParent().getElementType() == IJavaElement.FIELD) {
				EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
				if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null)  {
					return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
				}
			}
			ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
			if (creation != null) {
				if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
					return new ASTNode[] { creation.getParent() };
				} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
					return new ASTNode[] { creation};
				}
				return new ASTNode[] { creation.getAnonymousClassDeclaration() };
			}
			return new ASTNode[0];
		} else {
			ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
			// we have to delete the TypeDeclarationStatement
			nodes[0]= nodes[0].getParent();
			return nodes;
		}
	}
	return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}
 
@Override
public boolean visit(ClassInstanceCreation node) {
	doVisitChildren(node.typeArguments());
	doVisitNode(node.getType());
	evalQualifyingExpression(node.getExpression(), null);
	if (node.getAnonymousClassDeclaration() != null) {
		node.getAnonymousClassDeclaration().accept(this);
	}
	doVisitChildren(node.arguments());
	return false;
}
 
static boolean isFunctionalAnonymous(ClassInstanceCreation node) {
	ITypeBinding typeBinding= node.resolveTypeBinding();
	if (typeBinding == null)
		return false;
	ITypeBinding[] interfaces= typeBinding.getInterfaces();
	if (interfaces.length != 1)
		return false;
	if (interfaces[0].getFunctionalInterfaceMethod() == null)
		return false;

	AnonymousClassDeclaration anonymTypeDecl= node.getAnonymousClassDeclaration();
	if (anonymTypeDecl == null || anonymTypeDecl.resolveBinding() == null)
		return false;
	
	List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();
	// cannot convert if there are fields or additional methods
	if (bodyDeclarations.size() != 1)
		return false;
	BodyDeclaration bodyDeclaration= bodyDeclarations.get(0);
	if (!(bodyDeclaration instanceof MethodDeclaration))
		return false;

	MethodDeclaration methodDecl= (MethodDeclaration) bodyDeclaration;
	IMethodBinding methodBinding= methodDecl.resolveBinding();

	if (methodBinding == null)
		return false;
	// generic lambda expressions are not allowed
	if (methodBinding.isGenericMethod())
		return false;

	// lambda cannot refer to 'this'/'super' literals
	if (SuperThisReferenceFinder.hasReference(methodDecl))
		return false;
	
	if (!isInTargetTypeContext(node))
		return false;
	
	return true;
}
 
源代码14 项目: JDeodorant   文件: StyledStringVisitor.java
public boolean visit(ClassInstanceCreation expr) {
	/*
	 * 
	 * [ Expression . ] new [ < Type { , Type } > ] Type ( [ Expression { ,
	 * Expression } ] ) [ AnonymousClassDeclaration ]
	 */
	activateDiffStyle(expr);
	if (expr.getExpression() != null) {
		handleExpression(expr.getExpression());
		appendPeriod();
	}
	styledString.append("new", determineDiffStyle(expr, new StyledStringStyler(keywordStyle)));
	appendSpace();
	handleTypeArguments(expr.typeArguments());
	handleType(expr.getType());
	handleParameters(expr.arguments());
	if(expr.getAnonymousClassDeclaration() != null) {
		appendSpace();
		appendOpenCurlyBracket();
		for(int i=0; i<3; i++) {
			appendPeriod();
		}
		appendClosedCurlyBracket();
	}
	deactivateDiffStyle(expr);
	return false;
}
 
源代码15 项目: xtext-xtend   文件: JavaASTFlattener.java
@Override
public boolean visit(final ClassInstanceCreation node) {
  Expression _expression = node.getExpression();
  boolean _tripleNotEquals = (_expression != null);
  if (_tripleNotEquals) {
    node.getExpression().accept(this);
    this.appendToBuffer(".");
  }
  boolean _isLambdaCase = this._aSTFlattenerUtils.isLambdaCase(node);
  if (_isLambdaCase) {
    if (this.fallBackStrategy) {
      this.appendToBuffer("(");
    }
    this.appendToBuffer("[");
    Object _get = node.getAnonymousClassDeclaration().bodyDeclarations().get(0);
    final MethodDeclaration method = ((MethodDeclaration) _get);
    boolean _isEmpty = method.parameters().isEmpty();
    boolean _not = (!_isEmpty);
    if (_not) {
      this.visitAllSeparatedByComma(method.parameters());
      this.appendToBuffer("|");
    } else {
      if (this.fallBackStrategy) {
        this.appendToBuffer("|");
      }
    }
    this.visitAll(method.getBody().statements());
    this.appendToBuffer("]");
    if (this.fallBackStrategy) {
      this.appendToBuffer(" as ");
      boolean _isEmpty_1 = node.typeArguments().isEmpty();
      boolean _not_1 = (!_isEmpty_1);
      if (_not_1) {
        this.appendTypeParameters(node.typeArguments());
      }
      node.getType().accept(this);
      this.appendToBuffer(")");
    }
  } else {
    this.appendToBuffer("new ");
    boolean _isEmpty_2 = node.typeArguments().isEmpty();
    boolean _not_2 = (!_isEmpty_2);
    if (_not_2) {
      this.appendTypeParameters(node.typeArguments());
    }
    node.getType().accept(this);
    this.appendToBuffer("(");
    for (Iterator<Expression> it = node.arguments().iterator(); it.hasNext();) {
      {
        Expression e = it.next();
        e.accept(this);
        boolean _hasNext = it.hasNext();
        if (_hasNext) {
          this.appendToBuffer(",");
        }
      }
    }
    this.appendToBuffer(")");
    AnonymousClassDeclaration _anonymousClassDeclaration = node.getAnonymousClassDeclaration();
    boolean _tripleNotEquals_1 = (_anonymousClassDeclaration != null);
    if (_tripleNotEquals_1) {
      node.getAnonymousClassDeclaration().accept(this);
    }
  }
  return false;
}
 
/**
		 * {@inheritDoc}
		 */
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			ImportRemover importRemover= cuRewrite.getImportRemover();
			AST ast= rewrite.getAST();

			HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
			for (int i= 0; i < fExpressions.size(); i++) {
				ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
				TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);

				AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
				List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();

				Object object= bodyDeclarations.get(0);
				if (!(object instanceof MethodDeclaration))
					continue;
				MethodDeclaration methodDeclaration= (MethodDeclaration) object;
				HashSet<String> excludedNames= new HashSet<String>();
				if (i != 0) {
					for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
						if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
							excludedNames.addAll(cicToNewNames.get(convertedCic));
						}
					}
				}
				HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
				cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
				List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();

				// use short form with inferred parameter types and without parentheses if possible
				LambdaExpression lambdaExpression= ast.newLambdaExpression();
				List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
				lambdaExpression.setParentheses(methodParameters.size() != 1);
				for (SingleVariableDeclaration methodParameter : methodParameters) {
					VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
					lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
					lambdaParameters.add(lambdaParameter);
				}
				
				Block body= methodDeclaration.getBody();
				List<Statement> statements= body.statements();
				ASTNode lambdaBody= body;
				if (statements.size() == 1) {
					// use short form with just an expression body if possible
					Statement statement= statements.get(0);
					if (statement instanceof ExpressionStatement) {
						lambdaBody= ((ExpressionStatement) statement).getExpression();
					} else if (statement instanceof ReturnStatement) {
						Expression returnExpression= ((ReturnStatement) statement).getExpression();
						if (returnExpression != null) {
							lambdaBody= returnExpression;
						}
					}
				}
				//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
//				lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
				
				lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
				Expression replacement= lambdaExpression;
				if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
					CastExpression cast= ast.newCastExpression();
					cast.setExpression(lambdaExpression);
					ImportRewrite importRewrite= cuRewrite.getImportRewrite();
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
					Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
					cast.setType(castType);
					importRemover.registerAddedImports(castType);
					replacement= cast;
				}
				rewrite.replace(classInstanceCreation, replacement, group);

				importRemover.registerRemovedNode(classInstanceCreation);
				importRemover.registerRetainedNode(lambdaBody);
			}
		}
 
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final ASTRewrite rewrite= cuRewrite.getASTRewrite();
	VariableDeclarationFragment fragment= null;
	for (int i= 0; i < fNodes.length; i++) {
		final ASTNode node= fNodes[i];

		final AST ast= node.getAST();

		fragment= ast.newVariableDeclarationFragment();
		fragment.setName(ast.newSimpleName(NAME_FIELD));

		final FieldDeclaration declaration= ast.newFieldDeclaration(fragment);
		declaration.setType(ast.newPrimitiveType(PrimitiveType.LONG));
		declaration.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL));

		if (!addInitializer(fragment, node))
			continue;

		if (fragment.getInitializer() != null) {

			final TextEditGroup editGroup= createTextEditGroup(FixMessages.SerialVersion_group_description, cuRewrite);
			if (node instanceof AbstractTypeDeclaration)
				rewrite.getListRewrite(node, ((AbstractTypeDeclaration) node).getBodyDeclarationsProperty()).insertAt(declaration, 0, editGroup);
			else if (node instanceof AnonymousClassDeclaration)
				rewrite.getListRewrite(node, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
			else if (node instanceof ParameterizedType) {
				final ParameterizedType type= (ParameterizedType) node;
				final ASTNode parent= type.getParent();
				if (parent instanceof ClassInstanceCreation) {
					final ClassInstanceCreation creation= (ClassInstanceCreation) parent;
					final AnonymousClassDeclaration anonymous= creation.getAnonymousClassDeclaration();
					if (anonymous != null)
						rewrite.getListRewrite(anonymous, AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY).insertAt(declaration, 0, editGroup);
				}
			} else
				Assert.isTrue(false);

			addLinkedPositions(rewrite, fragment, positionGroups);
		}

		final String comment= CodeGeneration.getFieldComment(fUnit, declaration.getType().toString(), NAME_FIELD, StubUtility.getLineDelimiterUsed(fUnit));
		if (comment != null && comment.length() > 0) {
			final Javadoc doc= (Javadoc) rewrite.createStringPlaceholder(comment, ASTNode.JAVADOC);
			declaration.setJavadoc(doc);
		}
	}
	if (fragment == null)
		return;

	positionGroups.setEndPosition(rewrite.track(fragment));
}