下面列出了怎么用org.eclipse.jdt.core.dom.MethodInvocation的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public boolean visit(MethodInvocation node) {
if (inFrame) {
List arguments = node.arguments();
if (arguments.size() > 0) {
for (int i = 0; i < arguments.size(); i++) {
Expression exp = (Expression) arguments.get(i);
if (exp instanceof SimpleName) {
AbstractDebugVariableCodeMining<IJavaStackFrame> m = new JavaDebugElementCodeMining(
(SimpleName) exp, fFrame, viewer, provider);
minings.add(m);
}
}
}
}
return super.visit(node);
}
@Override
public boolean visit(MethodInvocation node) {
/*
* if (Utils.isGeneratedByLombok(node)) { return super.visit(node); }
*/
if (showParameterName || showParameterType) {
List arguments = node.arguments();
if (arguments.size() > 0 && acceptMethod(node)) {
for (int i = 0; i < arguments.size(); i++) {
Expression exp = (Expression) arguments.get(i);
if (showParameterOnlyForLiteral && !isLiteral(exp)) {
continue;
}
// Ignore empty parameter
if (exp instanceof SimpleName) {
if ("$missing$".equals(((SimpleName) exp).getIdentifier())) {
continue;
}
}
minings.add(new JavaMethodParameterCodeMining(node, exp, i, cu, provider, showParameterName,
showParameterType, showParameterByUsingFilters));
}
}
}
return super.visit(node);
}
private Statement createArrayComparison(String name) {
MethodInvocation invoc= fAst.newMethodInvocation();
invoc.setName(fAst.newSimpleName(METHODNAME_EQUALS));
invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS));
invoc.arguments().add(getThisAccessForEquals(name));
invoc.arguments().add(getOtherAccess(name));
PrefixExpression pe= fAst.newPrefixExpression();
pe.setOperator(PrefixExpression.Operator.NOT);
pe.setOperand(invoc);
IfStatement ifSt= fAst.newIfStatement();
ifSt.setExpression(pe);
ifSt.setThenStatement(getThenStatement(getReturnFalse()));
return ifSt;
}
protected void replaceThisExpressionWithContextParameterInMethodInvocationArguments(List<Expression> newMethodInvocations, AST subclassAST, ASTRewrite subclassRewriter) {
for(Expression expression : newMethodInvocations) {
if(expression instanceof MethodInvocation) {
MethodInvocation newMethodInvocation = (MethodInvocation)expression;
List<Expression> arguments = newMethodInvocation.arguments();
for(Expression argument : arguments) {
if(argument instanceof ThisExpression) {
String parameterName = sourceTypeDeclaration.getName().getIdentifier();
parameterName = parameterName.substring(0,1).toLowerCase() + parameterName.substring(1,parameterName.length());
ListRewrite argumentsRewrite = subclassRewriter.getListRewrite(newMethodInvocation, MethodInvocation.ARGUMENTS_PROPERTY);
argumentsRewrite.replace(argument, subclassAST.newSimpleName(parameterName), null);
}
}
}
}
}
private void modifyAccessToMethodsFromEnclosingInstance(CompilationUnitRewrite targetRewrite, MethodInvocation[] methodInvocations, AbstractTypeDeclaration declaration) {
IMethodBinding binding= null;
MethodInvocation invocation= null;
for (int index= 0; index < methodInvocations.length; index++) {
invocation= methodInvocations[index];
binding= invocation.resolveMethodBinding();
if (binding != null) {
final Expression target= invocation.getExpression();
if (target == null) {
final Expression expression= createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration);
targetRewrite.getASTRewrite().set(invocation, MethodInvocation.EXPRESSION_PROPERTY, expression, null);
} else {
if (!(invocation.getExpression() instanceof ThisExpression) || !(((ThisExpression) invocation.getExpression()).getQualifier() != null))
continue;
targetRewrite.getASTRewrite().replace(target, createAccessExpressionToEnclosingInstanceFieldText(invocation, binding, declaration), null);
targetRewrite.getImportRemover().registerRemovedNode(target);
}
}
}
}
private void replaceCastExpressionWithThisExpression(List<Expression> oldCastExpressions, List<Expression> newCastExpressions, TypeDeclaration subclassTypeDeclaration, AST subclassAST, ASTRewrite subclassRewriter) {
int j = 0;
for(Expression expression : oldCastExpressions) {
CastExpression castExpression = (CastExpression)expression;
if(castExpression.getType().resolveBinding().isEqualTo(subclassTypeDeclaration.resolveBinding())) {
if(castExpression.getExpression() instanceof SimpleName) {
SimpleName castSimpleName = (SimpleName)castExpression.getExpression();
if(typeVariable != null && typeVariable.getName().resolveBinding().isEqualTo(castSimpleName.resolveBinding())) {
subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
}
}
else if(castExpression.getExpression() instanceof MethodInvocation) {
MethodInvocation castMethodInvocation = (MethodInvocation)castExpression.getExpression();
if(typeMethodInvocation != null && typeMethodInvocation.subtreeMatch(new ASTMatcher(), castMethodInvocation)) {
subclassRewriter.replace(newCastExpressions.get(j), subclassAST.newThisExpression(), null);
}
}
}
j++;
}
}
/**
* createMarkerVisitor Creates the Visitor that goes through the unit and sets the Marker based on a case, which is currently hard coded as cypher.getinstance('AES').
*
* @param unit Unit from getUnitForParser
* @param cu same as unit but different type
* @return visitor for the unit
*/
private ASTVisitor createMarkerVisitor(final ICompilationUnit unit, final CompilationUnit cu) {
final ASTVisitor visitor = new ASTVisitor() {
@Override
public boolean visit(final MethodInvocation node) {
final int lineNumber = cu.getLineNumber(node.getStartPosition()) - 1;
if ("getInstance".equals(node.getName().toString()) && "Cipher".equals(node.getExpression().toString())) {
final List<Expression> l = node.arguments();
if (!l.isEmpty()) {
if ("AES".equals(l.get(0).resolveConstantExpressionValue()) && l.size() == 1) {
addMarker(unit.getResource(), "Error found", lineNumber, node.getStartPosition(), node.getStartPosition() + node.getLength());
}
}
}
return true;
}
};
return visitor;
}
private Set<Integer> findAllMethodCall(){
Set<Integer> methodStmt = new HashSet<>();
if(_backupBody != null){
Block body = _backupBody;
for(int i = 0; i < body.statements().size(); i++){
ASTNode stmt = (ASTNode) body.statements().get(i);
if(stmt instanceof ExpressionStatement){
stmt = ((ExpressionStatement) stmt).getExpression();
if(stmt instanceof MethodInvocation){
methodStmt.add(i);
} else if(stmt instanceof Assignment){
Assignment assign = (Assignment) stmt;
if(assign.getRightHandSide() instanceof MethodInvocation){
methodStmt.add(i);
}
}
}
}
}
return methodStmt;
}
public static Expression getExpression(ASTNode invocation) {
switch (invocation.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
return ((MethodInvocation)invocation).getExpression();
case ASTNode.SUPER_METHOD_INVOCATION:
return null;
case ASTNode.CONSTRUCTOR_INVOCATION:
return null;
case ASTNode.SUPER_CONSTRUCTOR_INVOCATION:
return ((SuperConstructorInvocation)invocation).getExpression();
case ASTNode.CLASS_INSTANCE_CREATION:
return ((ClassInstanceCreation)invocation).getExpression();
case ASTNode.ENUM_CONSTANT_DECLARATION:
return null;
default:
throw new IllegalArgumentException(invocation.toString());
}
}
/**
* {@inheritDoc}
*/
@Override
public boolean visit(MethodInvocation node) {
if (!fFindUnqualifiedMethodAccesses && !fFindUnqualifiedStaticMethodAccesses)
return true;
if (node.getExpression() != null)
return true;
IBinding binding= node.getName().resolveBinding();
if (!(binding instanceof IMethodBinding))
return true;
handleMethod(node.getName(), (IMethodBinding)binding);
return true;
}
/**
* Creates the corresponding statement for the method invocation, based on
* the return type.
*
* @param declaration the method declaration where the invocation statement
* is inserted
* @param invocation the method invocation being encapsulated by the
* resulting statement
* @return the corresponding statement
*/
protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) {
Assert.isNotNull(declaration);
Assert.isNotNull(invocation);
Statement statement= null;
final Type type= declaration.getReturnType2();
if (type == null) {
statement= createExpressionStatement(invocation);
} else {
if (type instanceof PrimitiveType) {
final PrimitiveType primitive= (PrimitiveType) type;
if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID)) {
statement= createExpressionStatement(invocation);
} else {
statement= createReturnStatement(invocation);
}
} else {
statement= createReturnStatement(invocation);
}
}
return statement;
}
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
if (node == null) {
return null;
}
switch (node.getNodeType()) {
case ASTNode.SIMPLE_NAME:
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
return node.getParent();
} else if (locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
}
return null;
case ASTNode.EXPRESSION_STATEMENT:
node = ((ExpressionStatement) node).getExpression();
}
switch (node.getNodeType()) {
case ASTNode.METHOD_DECLARATION:
return node;
case ASTNode.METHOD_INVOCATION:
case ASTNode.SUPER_METHOD_INVOCATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
}
return null;
}
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);
}
@Override
public boolean visit(MethodInvocation node) {
Expression expression= node.getExpression();
if (expression == null) {
IMethodBinding binding= node.resolveMethodBinding();
if (binding != null) {
if (isAccessToOuter(binding.getDeclaringClass())) {
fMethodAccesses.add(node);
}
}
} else {
expression.accept(this);
}
List<Expression> arguments= node.arguments();
for (int i= 0; i < arguments.size(); i++) {
arguments.get(i).accept(this);
}
return false;
}
/**
* Helper to generate an index based <code>for</code> loop to iterate over a {@link List}
* implementation.
*
* @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
* @return an applicable {@link ASTRewrite} instance
*/
private ASTRewrite generateIndexBasedForRewrite(AST ast) {
ASTRewrite rewrite= ASTRewrite.create(ast);
ForStatement loopStatement= ast.newForStatement();
SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
loopStatement.initializers().add(getForInitializer(ast, loopVariableName));
MethodInvocation listSizeExpression= ast.newMethodInvocation();
listSizeExpression.setName(ast.newSimpleName("size")); //$NON-NLS-1$
Expression listExpression= (Expression) rewrite.createCopyTarget(fCurrentExpression);
listSizeExpression.setExpression(listExpression);
loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), listSizeExpression, InfixExpression.Operator.LESS));
loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));
Block forLoopBody= ast.newBlock();
forLoopBody.statements().add(ast.newExpressionStatement(getIndexBasedForBodyAssignment(rewrite, loopVariableName)));
forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
loopStatement.setBody(forLoopBody);
rewrite.replace(fCurrentNode, loopStatement, null);
return rewrite;
}
public RefactoringStatus setCurrentMode(Mode mode) throws JavaModelException {
if (fCurrentMode == mode)
return new RefactoringStatus();
Assert.isTrue(getInitialMode() == Mode.INLINE_SINGLE);
fCurrentMode= mode;
if (mode == Mode.INLINE_SINGLE) {
if (fInitialNode instanceof MethodInvocation)
fTargetProvider= TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (MethodInvocation)fInitialNode);
else if (fInitialNode instanceof SuperMethodInvocation)
fTargetProvider= TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (SuperMethodInvocation)fInitialNode);
else if (fInitialNode instanceof ConstructorInvocation)
fTargetProvider= TargetProvider.create((ICompilationUnit) fInitialTypeRoot, (ConstructorInvocation)fInitialNode);
else
throw new IllegalStateException(String.valueOf(fInitialNode));
} else {
fTargetProvider= TargetProvider.create(fSourceProvider.getDeclaration());
}
return fTargetProvider.checkActivation();
}
@Override
public boolean visit(MethodInvocation node) {
IBinding binding= node.resolveMethodBinding();
if (isSourceAccess(binding)) {
if (isMovedMember(binding)) {
if (node.getExpression() != null)
rewrite(node, fTarget);
} else
rewrite(node, fSource);
} else if (isTargetAccess(binding)) {
if (node.getExpression() != null) {
fCuRewrite.getASTRewrite().remove(node.getExpression(), null);
fCuRewrite.getImportRemover().registerRemovedNode(node.getExpression());
}
}
return super.visit(node);
}
private IMethod getMethod(ASTNode node) throws JavaModelException {
IBinding binding;
if (node instanceof MethodInvocation) {
binding = ((MethodInvocation) node).resolveMethodBinding();
} else if (node instanceof MethodRef) {
binding = ((MethodRef) node).resolveBinding();
} else if (node instanceof ClassInstanceCreation) {
binding = ((ClassInstanceCreation) node).resolveConstructorBinding();
} else {
binding = null;
}
if (binding != null) {
IJavaElement javaElement = binding.getJavaElement();
if (javaElement instanceof IMethod) {
IMethod method = (IMethod) javaElement;
return method;
}
}
return null;
}
public static boolean isResolvedTypeInferredFromExpectedType(Expression invocation) {
if (invocation == null)
return false;
switch (invocation.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
return ((MethodInvocation) invocation).isResolvedTypeInferredFromExpectedType();
case ASTNode.SUPER_METHOD_INVOCATION:
return ((SuperMethodInvocation) invocation).isResolvedTypeInferredFromExpectedType();
case ASTNode.CLASS_INSTANCE_CREATION:
return ((ClassInstanceCreation) invocation).isResolvedTypeInferredFromExpectedType();
default:
return false;
}
}
protected boolean isTypeHolder(Object o) {
if(o.getClass().equals(MethodInvocation.class) || o.getClass().equals(SuperMethodInvocation.class)
|| o.getClass().equals(NumberLiteral.class) || o.getClass().equals(StringLiteral.class)
|| o.getClass().equals(CharacterLiteral.class) || o.getClass().equals(BooleanLiteral.class)
|| o.getClass().equals(TypeLiteral.class) || o.getClass().equals(NullLiteral.class)
|| o.getClass().equals(ArrayCreation.class)
|| o.getClass().equals(ClassInstanceCreation.class)
|| o.getClass().equals(ArrayAccess.class) || o.getClass().equals(FieldAccess.class)
|| o.getClass().equals(SuperFieldAccess.class) || o.getClass().equals(ParenthesizedExpression.class)
|| o.getClass().equals(SimpleName.class) || o.getClass().equals(QualifiedName.class)
|| o.getClass().equals(CastExpression.class) || o.getClass().equals(InfixExpression.class)
|| o.getClass().equals(PrefixExpression.class) || o.getClass().equals(InstanceofExpression.class)
|| o.getClass().equals(ThisExpression.class) || o.getClass().equals(ConditionalExpression.class))
return true;
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;
}
public RefactoringStatus setCurrentMode(Mode mode) throws JavaModelException {
if (fTargetProvider.isSingle() == (mode == Mode.REPLACE_SINGLE))
return new RefactoringStatus();
Assert.isTrue(canReplaceSingle());
if (mode == Mode.REPLACE_SINGLE) {
fTargetProvider= TargetProvider.create((ICompilationUnit) fSelectionTypeRoot, (MethodInvocation) fSelectionNode);
} else {
fTargetProvider= TargetProvider.create(fSourceProvider.getDeclaration());
}
return fTargetProvider.checkActivation();
}
/**
* {@inheritDoc}
*/
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
TextEditGroup group= createTextEditGroup(FixMessages.CodeStyleFix_ChangeAccessUsingDeclaring_description, cuRewrite);
if (fQualifier instanceof MethodInvocation || fQualifier instanceof ClassInstanceCreation)
extractQualifier(fQualifier, cuRewrite, group);
Type type= importType(fDeclaringTypeBinding, fQualifier, cuRewrite.getImportRewrite(), cuRewrite.getRoot());
cuRewrite.getASTRewrite().replace(fQualifier, type, group);
}
protected Expression createSubListInvocation(Expression memberAccess, Expression sizeAccess) {
MethodInvocation subListInvocation= fAst.newMethodInvocation();
subListInvocation.setExpression(memberAccess);
subListInvocation.setName(fAst.newSimpleName("subList")); //$NON-NLS-1$
subListInvocation.arguments().add(fAst.newNumberLiteral(String.valueOf(0)));
MethodInvocation minInvocation= createMethodInvocation(addImport("java.lang.Math"), "min", sizeAccess); //$NON-NLS-1$ //$NON-NLS-2$
minInvocation.arguments().add(fAst.newSimpleName(fMaxLenVariableName));
subListInvocation.arguments().add(minInvocation);
needMaxLenVariable= true;
return subListInvocation;
}
public static Entry get(Expression type) {
ITypeBinding ib = type.resolveTypeBinding();
if(ib == null) {
if(type instanceof MethodInvocation) {
IMethodBinding mi = ((MethodInvocation)type).resolveMethodBinding();
if(mi != null) ib = mi.getReturnType();
}
}
if(ib == null) {
CompilerError.exec(CompilerError.TYPE_NOT_FOUND, type.toString() + ", " + type.getClass());
return null;
}
else return get(ib);
}
public Expression createFieldWriteAccess(ParameterInfo pi, String paramName, AST ast, IJavaProject project, Expression assignedValue, boolean useSuper, Expression qualifier) {
Expression completeQualifier= generateQualifier(paramName, ast, useSuper, qualifier);
if (fCreateSetter) {
MethodInvocation mi= ast.newMethodInvocation();
mi.setName(ast.newSimpleName(getSetterName(pi, ast, project)));
mi.setExpression(completeQualifier);
mi.arguments().add(assignedValue);
return mi;
}
return createFieldAccess(pi, ast, completeQualifier);
}
@Override
public boolean validElement(ASTNode curElement) {
if (super.validElement(curElement)) {
String fullName = ExporterUtils.getFullyQualifiedName((MethodInvocation) curElement);
return fullName.equals("hu.elte.txtuml.api.model.seqdiag.Sequence.assertSend")
|| fullName.equals("hu.elte.txtuml.api.model.seqdiag.Sequence.fromActor");
}
return false;
}
private static Integer getTernaryArgumentIndex(MethodInvocation ternaryMethodInvocation, ConditionalExpression conditionalExpression)
{
List<Expression> arguments = ternaryMethodInvocation.arguments();
for (int i = 0; i < arguments.size(); i++)
{
if (arguments.get(i).equals(conditionalExpression))
{
return i;
}
}
return null;
}
public static Type getReturnTypeFromInvocation(MethodInvocation methodInvocation) {
IMethodBinding binding = methodInvocation.resolveMethodBinding();
try {
CompilationUnit cu = getCompilationUnit(binding);
MethodDeclaration decl = (MethodDeclaration) cu.findDeclaringNode(binding.getKey());
Type returnType = decl.getReturnType2();
return returnType;
} catch (NullPointerException ex) {
return null;
}
}
/**
* End of visit the return type of a method invocation.
*
* @param invocation the method invocation
* @param binding the method binding
*/
private void endVisit(final MethodInvocation invocation, final IMethodBinding binding) {
if (!binding.isConstructor()) {
final ConstraintVariable2 variable= fModel.createReturnTypeVariable(binding);
if (variable != null)
invocation.setProperty(PROPERTY_CONSTRAINT_VARIABLE, variable);
}
}