Java Code Examples for org.eclipse.jdt.core.dom.IMethodBinding#getName()

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding#getName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: APIMethodData.java    From SnowGraph with Apache License 2.0 6 votes vote down vote up
public void initByIMethodBinding(IMethodBinding mBinding) {
	IMethod iMethod = (IMethod) mBinding.getJavaElement();
	try {
		key = iMethod.getKey().substring(0, iMethod.getKey().indexOf("("))
				+ iMethod.getSignature();
		projectName = mBinding.getJavaElement().getJavaProject()
				.getElementName();
	} catch (Exception e) {
		projectName = "";
	}
	packageName = mBinding.getDeclaringClass().getPackage().getName();
	className = mBinding.getDeclaringClass().getName();
	name = mBinding.getName();

	parameters = new ArrayList<>();
	ITypeBinding[] parameterBindings = mBinding.getParameterTypes();
	for (int i = 0; i < parameterBindings.length; i++) {
		parameters.add(parameterBindings[i].getName());
	}
}
 
Example 2
Source File: JUnit3Adapter.java    From sahagin-java with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRootMethod(IMethodBinding methodBinding) {
    // TODO should check if public and no argument and void return method
    String methodName = methodBinding.getName();
    if (methodName == null || !methodName.startsWith("test")) {
        return false;
    }

    ITypeBinding defClass = methodBinding.getDeclaringClass();
    while (defClass != null) {
        String className = defClass.getQualifiedName();
        if ("junit.framework.TestCase".equals(className)) {
            return true;
        }
        defClass = defClass.getSuperclass();
    }
    return false;
}
 
Example 3
Source File: AstUtils.java    From RefactoringMiner with MIT License 6 votes vote down vote up
public static String getKeyFromMethodBinding(IMethodBinding binding) {
	StringBuilder sb = new StringBuilder();
	String className = binding.getDeclaringClass().getErasure().getQualifiedName();
	sb.append(className);
	sb.append('#');
	String methodName = binding.isConstructor() ? "" : binding.getName();
	sb.append(methodName);
	//if (methodName.equals("allObjectsSorted")) {
	//	System.out.println();
	//}
	sb.append('(');
	ITypeBinding[] parameters = binding.getParameterTypes();
	for (int i = 0; i < parameters.length; i++) {
		if (i > 0) {
			sb.append(", ");
		}
		ITypeBinding type = parameters[i];
		sb.append(type.getErasure().getName());
	}
	sb.append(')');
	return sb.toString();
}
 
Example 4
Source File: AsynchronousInterfaceValidator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected List<CategorizedProblem> doValidateMethodOnDependentInterface(
    IMethodBinding methodBinding, TypeDeclaration changedInterface,
    ITypeBinding dependentInterfaceBinding) {
  String[] parameters = RemoteServiceUtilities.computeAsyncParameterTypes(methodBinding);
  String methodName = methodBinding.getName();
  if (Bindings.findMethodInHierarchy(changedInterface.resolveBinding(),
      methodName, parameters) == null) {
    CategorizedProblem problem = RemoteServiceProblemFactory.newMissingAsyncMethodOnAsync(
        methodBinding, changedInterface);
    if (problem != null) {
      return Collections.singletonList(problem);
    }
  }

  return Collections.emptyList();
}
 
Example 5
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @since 2.4
 */
protected JvmOperation createMethodProxy(ITypeBinding typeBinding, IMethodBinding method) {
	JvmOperation proxy = operationProxies.get(method);
	if (proxy == null) {
		String methodName = method.getName();
		URI uri = uriHelper.getFullURI(typeBinding, methodName);
		JvmOperation[] jvmOperations = ANNOTATION_METHOD_PROXIES.get(uri.lastSegment());
		if (jvmOperations != null) {
			for (JvmOperation jvmOperation : jvmOperations) {
				String fragment = ((InternalEObject)jvmOperation).eProxyURI().fragment();
				if (fragment.startsWith(methodName, fragment.length() - methodName.length() - 2)) {
					operationProxies.put(method, jvmOperation);
					return jvmOperation;
				}
			}
		}
		proxy = TypesFactory.eINSTANCE.createJvmOperation();
		((InternalEObject)proxy).eSetProxyURI(uri);
		operationProxies.put(method, proxy);
	}
	return proxy;
}
 
Example 6
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static void checkName(RefactoringStatus status, String name, List<IMethodBinding> usedNames, IType type, boolean reUseExistingField, IField field) {
	if ("".equals(name)) { //$NON-NLS-1$
		status.addFatalError(RefactoringCoreMessages.Checks_Choose_name);
		return;
	}
	boolean isStatic = false;
	try {
		isStatic = Flags.isStatic(field.getFlags());
	} catch (JavaModelException e) {
		JavaLanguageServerPlugin.log(e);
	}
	status.merge(Checks.checkMethodName(name, field));
	for (Iterator<IMethodBinding> iter = usedNames.iterator(); iter.hasNext();) {
		IMethodBinding method = iter.next();
		String selector = method.getName();
		if (selector.equals(name)) {
			if (!reUseExistingField) {
				status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_method_exists,
						new String[] { BindingLabelProviderCore.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(type.getElementName()) }));
			} else {
				boolean methodIsStatic = Modifier.isStatic(method.getModifiers());
				if (methodIsStatic && !isStatic) {
					status.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field,
							new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				}
				if (!methodIsStatic && isStatic) {
					status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				}
				return;
			}

		}
	}
	if (reUseExistingField) {
		status.addFatalError(Messages.format(
			RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError,
			new String[] { BasicElementLabels.getJavaElementName(name), BasicElementLabels.getJavaElementName(type.getElementName())}));
	}
}
 
Example 7
Source File: SelfEncapsulateFieldRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static boolean checkName(String name, List<IMethodBinding> usedNames) {
	for (Iterator<IMethodBinding> iter = usedNames.iterator(); iter.hasNext();) {
		IMethodBinding method = iter.next();
		String selector = method.getName();
		if (selector.equals(name)) {
			return true;
		}
	}
	return false;
}
 
Example 8
Source File: OverrideMethodsOperation.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static OverridableMethod convertToSerializableMethod(IMethodBinding binding, boolean unimplemented) {
	OverridableMethod result = new OverridableMethod();
	result.bindingKey = binding.getKey();
	result.name = binding.getName();
	result.parameters = getMethodParameterTypes(binding, false);
	result.unimplemented = unimplemented || Modifier.isAbstract(binding.getModifiers());
	result.declaringClass = binding.getDeclaringClass().getQualifiedName();
	result.declaringClassType = binding.getDeclaringClass().isInterface() ? "interface" : "class";
	return result;
}
 
Example 9
Source File: InJavaImporter.java    From jdt2famix with Eclipse Public License 1.0 5 votes vote down vote up
public Method ensureMethodFromMethodBinding(IMethodBinding binding, Type parentType) {
	StringJoiner signatureJoiner = new StringJoiner(", ", "(", ")");
	Arrays.stream(binding.getParameterTypes()).forEach(p -> signatureJoiner.add((String) p.getQualifiedName()));
	String methodName = binding.getName();
	String signature = methodName + signatureJoiner.toString();
	return ensureBasicMethod(methodName, signature, parentType, m -> setUpMethodFromMethodBinding(m, binding));
}
 
Example 10
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void checkName(RefactoringStatus status, String name, List<IMethodBinding> usedNames, IType type, boolean reUseExistingField, IField field) {
	if ("".equals(name)) { //$NON-NLS-1$
		status.addFatalError(RefactoringCoreMessages.Checks_Choose_name);
		return;
    }
	boolean isStatic=false;
	try {
		isStatic= Flags.isStatic(field.getFlags());
	} catch (JavaModelException e) {
		JavaPlugin.log(e);
	}
	status.merge(Checks.checkMethodName(name, field));
	for (Iterator<IMethodBinding> iter= usedNames.iterator(); iter.hasNext(); ) {
		IMethodBinding method= iter.next();
		String selector= method.getName();
		if (selector.equals(name)) {
			if (!reUseExistingField) {
				status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateField_method_exists, new String[] { BindingLabelProvider.getBindingLabel(method, JavaElementLabels.ALL_FULLY_QUALIFIED), BasicElementLabels.getJavaElementName(type.getElementName()) }));
			} else {
				boolean methodIsStatic= Modifier.isStatic(method.getModifiers());
				if (methodIsStatic && !isStatic)
					status.addWarning(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_static_method_but_nonstatic_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				if (!methodIsStatic && isStatic)
					status.addFatalError(Messages.format(RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_nonstatic_method_but_static_field, new String[] { BasicElementLabels.getJavaElementName(method.getName()), BasicElementLabels.getJavaElementName(field.getElementName()) }));
				return;
			}

		}
	}
	if (reUseExistingField)
		status.addFatalError(Messages.format(
			RefactoringCoreMessages.SelfEncapsulateFieldRefactoring_methoddoesnotexist_status_fatalError,
			new String[] { BasicElementLabels.getJavaElementName(name), BasicElementLabels.getJavaElementName(type.getElementName())}));
}
 
Example 11
Source File: SelfEncapsulateFieldRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean checkName(String name, List<IMethodBinding> usedNames) {
	for (Iterator<IMethodBinding> iter= usedNames.iterator(); iter.hasNext(); ) {
		IMethodBinding method= iter.next();
		String selector= method.getName();
		if (selector.equals(name)) {
			return true;
		}
	}
	return false;
}
 
Example 12
Source File: SrcTreeGenerator.java    From sahagin-java with Apache License 2.0 5 votes vote down vote up
private String generateMethodKey(IMethodBinding method, boolean noArgClassesStr) {
    String classQualifiedName = method.getDeclaringClass().getBinaryName();
    String methodSimpleName = method.getName();
    List<String> argClassQualifiedNames = getArgClassQualifiedNames(method);
    if (noArgClassesStr) {
        return TestMethod.generateMethodKey(classQualifiedName, methodSimpleName);
    } else {
        return TestMethod.generateMethodKey(
                classQualifiedName, methodSimpleName, argClassQualifiedNames);
    }
}
 
Example 13
Source File: AbstractMethodFragment.java    From JDeodorant with MIT License 5 votes vote down vote up
protected void processConstructorInvocation(ConstructorInvocation constructorInvocation) {
	IMethodBinding methodBinding = constructorInvocation.resolveConstructorBinding();
	String originClassName = methodBinding.getDeclaringClass().getQualifiedName();
	TypeObject originClassTypeObject = TypeObject.extractTypeObject(originClassName);
	String methodInvocationName = methodBinding.getName();
	String qualifiedName = methodBinding.getReturnType().getQualifiedName();
	TypeObject returnType = TypeObject.extractTypeObject(qualifiedName);
	ConstructorInvocationObject constructorInvocationObject = new ConstructorInvocationObject(originClassTypeObject, methodInvocationName, returnType);
	constructorInvocationObject.setConstructorInvocation(constructorInvocation);
	ITypeBinding[] parameterTypes = methodBinding.getParameterTypes();
	for(ITypeBinding parameterType : parameterTypes) {
		String qualifiedParameterName = parameterType.getQualifiedName();
		TypeObject typeObject = TypeObject.extractTypeObject(qualifiedParameterName);
		constructorInvocationObject.addParameter(typeObject);
	}
	ITypeBinding[] thrownExceptionTypes = methodBinding.getExceptionTypes();
	for(ITypeBinding thrownExceptionType : thrownExceptionTypes) {
		constructorInvocationObject.addThrownException(thrownExceptionType.getQualifiedName());
	}
	if((methodBinding.getModifiers() & Modifier.STATIC) != 0)
		constructorInvocationObject.setStatic(true);
	addConstructorInvocation(constructorInvocationObject);
	List<Expression> arguments = constructorInvocation.arguments();
	for(Expression argument : arguments) {
		if(argument instanceof SimpleName) {
			SimpleName argumentName = (SimpleName)argument;
			IBinding binding = argumentName.resolveBinding();
			if(binding != null && binding.getKind() == IBinding.VARIABLE) {
				IVariableBinding variableBinding = (IVariableBinding)binding;
				if(variableBinding.isParameter()) {
					PlainVariable variable = new PlainVariable(variableBinding);
					addParameterPassedAsArgumentInConstructorInvocation(variable, constructorInvocationObject);
				}
			}
		}
	}
}
 
Example 14
Source File: JdtDomModels.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
public LspMethodBinding(IMethodBinding binding) {
	this.bindingKey = binding.getKey();
	this.name = binding.getName();
	this.parameters = Stream.of(binding.getParameterTypes()).map(type -> type.getName()).toArray(String[]::new);
}
 
Example 15
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @since 2.4
 */
protected void enhanceExecutable(StringBuilder fqn, String handleIdentifier, String[] path, JvmExecutable result, IMethodBinding method) {
	String name = method.getName();
	fqn.append(name);
	fqn.append('(');
	ITypeBinding[] parameterTypes = method.getParameterTypes();
	for (int i = 0; i < parameterTypes.length; i++) {
		if (i != 0)
			fqn.append(',');
		fqn.append(getQualifiedName(parameterTypes[i]));
	}
	fqn.append(')');
	result.internalSetIdentifier(fqn.toString());
	result.setSimpleName(name);
	setVisibility(result, method.getModifiers());
	result.setDeprecated(method.isDeprecated());
	if (parameterTypes.length > 0) {
		result.setVarArgs(method.isVarargs());
		String[] parameterNames = null;

		// If the method is derived from source, we can efficiently determine the parameter names now.
		//
		ITypeBinding declaringClass = method.getDeclaringClass();
		if (declaringClass.isFromSource()) {
			parameterNames = getParameterNamesFromSource(fqn, method);
		} else {
			// Use the key to determine the signature for the method.
			//
			SegmentSequence signaturex = getSignatureAsSegmentSequence(method);
			ParameterNameInitializer initializer = jdtCompliance.createParameterNameInitializer(method, workingCopyOwner, result, handleIdentifier, path, name, signaturex);
			((JvmExecutableImplCustom)result).setParameterNameInitializer(initializer);
		}

		setParameterNamesAndAnnotations(method, parameterTypes, parameterNames, result);
	}

	ITypeBinding[] exceptionTypes = method.getExceptionTypes();
	if (exceptionTypes.length > 0) {
		InternalEList<JvmTypeReference> exceptions = (InternalEList<JvmTypeReference>)result.getExceptions();
		for (ITypeBinding exceptionType : exceptionTypes) {
			exceptions.addUnique(createTypeReference(exceptionType));
		}
	}
}
 
Example 16
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
 * place of direct calls to the constructor in question.
 * 
 * @param ast An AST used as a factory for various AST nodes
 * @param ctorBinding binding for the constructor being wrapped
 * @param unitRewriter the ASTRewrite to be used
 * @return the new method declaration
 * @throws CoreException if an exception occurs while accessing its corresponding resource
 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException{
	MethodDeclaration		newMethod= ast.newMethodDeclaration();
	SimpleName				newMethodName= ast.newSimpleName(fNewMethodName);
	ClassInstanceCreation	newCtorCall= ast.newClassInstanceCreation();
	ReturnStatement			ret= ast.newReturnStatement();
	Block		body= ast.newBlock();
	List<Statement>		stmts= body.statements();
	String		retTypeName= ctorBinding.getName();

	createFactoryMethodSignature(ast, newMethod);

	newMethod.setName(newMethodName);
	newMethod.setBody(body);

	ITypeBinding declaringClass= fCtorBinding.getDeclaringClass();
	ITypeBinding[] ctorOwnerTypeParameters= declaringClass.getTypeParameters();

	setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);

	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));

	setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);

	createFactoryMethodConstructorArgs(ast, newCtorCall);

	if (Modifier.isAbstract(declaringClass.getModifiers())) {
		AnonymousClassDeclaration decl= ast.newAnonymousClassDeclaration();
		IMethodBinding[] unimplementedMethods= getUnimplementedMethods(declaringClass);
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
		for (int i= 0; i < unimplementedMethods.length; i++) {
			IMethodBinding unImplementedMethod= unimplementedMethods[i];
			MethodDeclaration newMethodDecl= StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass()
					.getName(), settings, false);
			decl.bodyDeclarations().add(newMethodDecl);
		}
		newCtorCall.setAnonymousClassDeclaration(decl);
	}

	ret.setExpression(newCtorCall);
	stmts.add(ret);

	return newMethod;
}
 
Example 17
Source File: StubUtility2.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
public static MethodDeclaration createDelegationStub(ICompilationUnit unit, ASTRewrite rewrite, ImportRewrite imports, ImportRewriteContext context, IMethodBinding delegate, IVariableBinding delegatingField, CodeGenerationSettings settings) throws CoreException {
	Assert.isNotNull(delegate);
	Assert.isNotNull(delegatingField);
	Assert.isNotNull(settings);

	AST ast= rewrite.getAST();

	MethodDeclaration decl= ast.newMethodDeclaration();
	decl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, delegate.getModifiers() & ~Modifier.SYNCHRONIZED & ~Modifier.ABSTRACT & ~Modifier.NATIVE));

	decl.setName(ast.newSimpleName(delegate.getName()));
	decl.setConstructor(false);

	createTypeParameters(imports, context, ast, delegate, decl);

	decl.setReturnType2(imports.addImport(delegate.getReturnType(), ast, context));

	List<SingleVariableDeclaration> params= createParameters(unit.getJavaProject(), imports, context, ast, delegate, null, decl);

	createThrownExceptions(decl, delegate, imports, context, ast);

	Block body= ast.newBlock();
	decl.setBody(body);

	String delimiter= StubUtility.getLineDelimiterUsed(unit);

	Statement statement= null;
	MethodInvocation invocation= ast.newMethodInvocation();
	invocation.setName(ast.newSimpleName(delegate.getName()));
	List<Expression> arguments= invocation.arguments();
	for (int i= 0; i < params.size(); i++)
		arguments.add(ast.newSimpleName(params.get(i).getName().getIdentifier()));
	if (settings.useKeywordThis) {
		FieldAccess access= ast.newFieldAccess();
		access.setExpression(ast.newThisExpression());
		access.setName(ast.newSimpleName(delegatingField.getName()));
		invocation.setExpression(access);
	} else
		invocation.setExpression(ast.newSimpleName(delegatingField.getName()));
	if (delegate.getReturnType().isPrimitive() && delegate.getReturnType().getName().equals("void")) {//$NON-NLS-1$
		statement= ast.newExpressionStatement(invocation);
	} else {
		ReturnStatement returnStatement= ast.newReturnStatement();
		returnStatement.setExpression(invocation);
		statement= returnStatement;
	}
	body.statements().add(statement);

	ITypeBinding declaringType= delegatingField.getDeclaringClass();
	if (declaringType == null) { // can be null for
		return decl;
	}

	String qualifiedName= declaringType.getQualifiedName();
	IPackageBinding packageBinding= declaringType.getPackage();
	if (packageBinding != null) {
		if (packageBinding.getName().length() > 0 && qualifiedName.startsWith(packageBinding.getName()))
			qualifiedName= qualifiedName.substring(packageBinding.getName().length());
	}

	if (settings.createComments) {
		/*
		 * TODO: have API for delegate method comments This is an inlined
		 * version of
		 * {@link CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String)}
		 */
		delegate= delegate.getMethodDeclaration();
		String declaringClassQualifiedName= delegate.getDeclaringClass().getQualifiedName();
		String linkToMethodName= delegate.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(delegate);
		String string= StubUtility.getMethodComment(unit, qualifiedName, decl, delegate.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, true, delimiter);
		if (string != null) {
			Javadoc javadoc= (Javadoc) rewrite.createStringPlaceholder(string, ASTNode.JAVADOC);
			decl.setJavadoc(javadoc);
		}
	}
	return decl;
}
 
Example 18
Source File: JdtUtils.java    From j2cl with Apache License 2.0 4 votes vote down vote up
/** Create a MethodDescriptor directly based on the given JDT method binding. */
public static MethodDescriptor createMethodDescriptor(IMethodBinding methodBinding) {
  if (methodBinding == null) {
    return null;
  }

  DeclaredTypeDescriptor enclosingTypeDescriptor =
      createDeclaredTypeDescriptor(methodBinding.getDeclaringClass());

  boolean isStatic = isStatic(methodBinding);
  Visibility visibility = getVisibility(methodBinding);
  boolean isDefault = isDefaultMethod(methodBinding);
  JsInfo jsInfo = computeJsInfo(methodBinding);

  boolean isNative =
      Modifier.isNative(methodBinding.getModifiers())
          || (!jsInfo.isJsOverlay()
              && enclosingTypeDescriptor.isNative()
              && isAbstract(methodBinding));

  boolean isConstructor = methodBinding.isConstructor();
  String methodName = methodBinding.getName();

  TypeDescriptor returnTypeDescriptor =
      createTypeDescriptorWithNullability(
          methodBinding.getReturnType(), methodBinding.getAnnotations());

  MethodDescriptor declarationMethodDescriptor = null;
  if (methodBinding.getMethodDeclaration() != methodBinding) {
    // The declaration for methods in a lambda binding is two hops away. Since the declaration
    // binding of a declaration is itself, we get the declaration of the declaration here.
    IMethodBinding declarationBinding =
        methodBinding.getMethodDeclaration().getMethodDeclaration();
    declarationMethodDescriptor = createMethodDescriptor(declarationBinding);
  }

  // generate type parameters declared in the method.
  Iterable<TypeVariable> typeParameterTypeDescriptors =
      FluentIterable.from(methodBinding.getTypeParameters())
          .transform(JdtUtils::createTypeDescriptor)
          .transform(typeDescriptor -> (TypeVariable) typeDescriptor);

  ImmutableList.Builder<ParameterDescriptor> parameterDescriptorBuilder = ImmutableList.builder();
  for (int i = 0; i < methodBinding.getParameterTypes().length; i++) {
    parameterDescriptorBuilder.add(
        ParameterDescriptor.newBuilder()
            .setTypeDescriptor(
                createTypeDescriptorWithNullability(
                    methodBinding.getParameterTypes()[i],
                    methodBinding.getParameterAnnotations(i)))
            .setJsOptional(JsInteropUtils.isJsOptional(methodBinding, i))
            .setVarargs(
                i == methodBinding.getParameterTypes().length - 1 && methodBinding.isVarargs())
            .setDoNotAutobox(JsInteropUtils.isDoNotAutobox(methodBinding, i))
            .build());
  }

  if (enclosingTypeDescriptor.getTypeDeclaration().isAnonymous()
      && isConstructor
      && enclosingTypeDescriptor.getSuperTypeDescriptor().hasJsConstructor()) {
    jsInfo = JsInfo.Builder.from(jsInfo).setJsMemberType(JsMemberType.CONSTRUCTOR).build();
  }
  return MethodDescriptor.newBuilder()
      .setEnclosingTypeDescriptor(enclosingTypeDescriptor)
      .setName(isConstructor ? null : methodName)
      .setParameterDescriptors(parameterDescriptorBuilder.build())
      .setDeclarationDescriptor(declarationMethodDescriptor)
      .setReturnTypeDescriptor(returnTypeDescriptor)
      .setTypeParameterTypeDescriptors(typeParameterTypeDescriptors)
      .setJsInfo(jsInfo)
      .setJsFunction(isOrOverridesJsFunctionMethod(methodBinding))
      .setVisibility(visibility)
      .setStatic(isStatic)
      .setConstructor(isConstructor)
      .setNative(isNative)
      .setFinal(JdtUtils.isFinal(methodBinding))
      .setDefaultMethod(isDefault)
      .setAbstract(Modifier.isAbstract(methodBinding.getModifiers()))
      .setSynthetic(methodBinding.isSynthetic())
      .setEnumSyntheticMethod(isEnumSyntheticMethod(methodBinding))
      .setUnusableByJsSuppressed(JsInteropAnnotationUtils.isUnusableByJsSuppressed(methodBinding))
      .setDeprecated(isDeprecated(methodBinding))
      .build();
}
 
Example 19
Source File: CodeGeneration.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 3 votes vote down vote up
/**
 * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method).
 * <code>null</code> is returned if the template is empty.
 * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist.
 * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer
 * types names (dot separated). See {@link org.eclipse.jdt.core.IType#getTypeQualifiedName(char)}.
 * @param decl The MethodDeclaration AST node that will be added as new
 * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve.
 * See {@link org.eclipse.jdt.core.dom.AST#newMethodDeclaration()} for how to create such a node.
 * @param overridden The binding of the method to which to add an "@see" link or
 * <code>null</code> if no link should be created.
 * @param lineDelimiter The line delimiter to be used.
 * @return Returns the generated method comment or <code>null</code> if the
 * code template is empty. The returned content is unformatted and not indented (formatting required).
 * @throws CoreException Thrown when the evaluation of the code template fails.
 */
public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, MethodDeclaration decl, IMethodBinding overridden, String lineDelimiter) throws CoreException {
	if (overridden != null) {
		overridden= overridden.getMethodDeclaration();
		String declaringClassQualifiedName= overridden.getDeclaringClass().getQualifiedName();
		String linkToMethodName= overridden.getName();
		String[] parameterTypesQualifiedNames= StubUtility.getParameterTypeNamesForSeeTag(overridden);
		return StubUtility.getMethodComment(cu, declaringTypeName, decl, overridden.isDeprecated(), linkToMethodName, declaringClassQualifiedName, parameterTypesQualifiedNames, false, lineDelimiter);
	} else {
		return StubUtility.getMethodComment(cu, declaringTypeName, decl, false, null, null, null, false, lineDelimiter);
	}
}