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

The following examples show how to use org.eclipse.jdt.core.dom.IMethodBinding#isConstructor() . 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: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Checks if the new method is already used in the given type.
 * @param type
 * @param methodName
 * @param parameters
 * @return the status
 */
public static RefactoringStatus checkMethodInType(ITypeBinding type, String methodName, ITypeBinding[] parameters) {
	RefactoringStatus result= new RefactoringStatus();
	IMethodBinding method= org.eclipse.jdt.internal.corext.dom.Bindings.findMethodInType(type, methodName, parameters);
	if (method != null) {
		if (method.isConstructor()) {
			result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
					new Object[] { BasicElementLabels.getJavaElementName(type.getName()) }));
		} else {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_exists,
					new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(type.getName()) }),
					JavaStatusContext.create(method));
		}
	}
	return result;
}
 
Example 2
Source File: JdtTypeProviderTest.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
private boolean isParameterNamesAvailable() throws Exception {
	ASTParser parser = ASTParser.newParser(AST.JLS3);
	parser.setIgnoreMethodBodies(true);
	IJavaProject javaProject = projectProvider.getJavaProject(resourceSet);
	parser.setProject(javaProject);
	IType type = javaProject.findType("org.eclipse.xtext.common.types.testSetups.TestEnum");
	IBinding[] bindings = parser.createBindings(new IJavaElement[] { type }, null);
	ITypeBinding typeBinding = (ITypeBinding) bindings[0];
	IMethodBinding[] methods = typeBinding.getDeclaredMethods();
	for(IMethodBinding method: methods) {
		if (method.isConstructor()) {
			IMethod element = (IMethod) method.getJavaElement();
			if (element.exists()) {
				String[] parameterNames = element.getParameterNames();
				if (parameterNames.length == 1 && parameterNames[0].equals("string")) {
					return true;
				}
			} else {
				return false;
			}
		}
	}
	return false;
}
 
Example 3
Source File: SemanticHighlightings.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean consumes(SemanticToken token) {
	IBinding binding= getBinding(token);
	if (binding != null) {
		if (binding.isDeprecated())
			return true;
		if (binding instanceof IMethodBinding) {
			IMethodBinding methodBinding= (IMethodBinding) binding;
			if (methodBinding.isConstructor() && methodBinding.getJavaElement() == null) {
				ITypeBinding declaringClass= methodBinding.getDeclaringClass();
				if (declaringClass.isAnonymous()) {
					ITypeBinding[] interfaces= declaringClass.getInterfaces();
					if (interfaces.length > 0)
						return interfaces[0].isDeprecated();
					else
						return declaringClass.getSuperclass().isDeprecated();
				}
				return declaringClass.isDeprecated();
			}
		}
	}
	return false;
}
 
Example 4
Source File: ConvertAnonymousToNestedRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private IMethodBinding getSuperConstructorBinding() {
    //workaround for missing java core functionality - finding a
    // super constructor for an anonymous class creation
    IMethodBinding anonConstr= ((ClassInstanceCreation) fAnonymousInnerClassNode.getParent()).resolveConstructorBinding();
    if (anonConstr == null)
        return null;
    ITypeBinding superClass= anonConstr.getDeclaringClass().getSuperclass();
    IMethodBinding[] superMethods= superClass.getDeclaredMethods();
    for (int i= 0; i < superMethods.length; i++) {
        IMethodBinding superMethod= superMethods[i];
        if (superMethod.isConstructor() && parameterTypesMatch(superMethod, anonConstr))
            return superMethod;
    }
    Assert.isTrue(false);//there's no way - it must be there
    return null;
}
 
Example 5
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 6
Source File: Checks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the new method somehow conflicts with an already existing method in
 * the hierarchy. The following checks are done:
 * <ul>
 *   <li> if the new method overrides a method defined in the given type or in one of its
 * 		super classes. </li>
 * </ul>
 * @param type
 * @param methodName
 * @param returnType
 * @param parameters
 * @return the status
 */
public static RefactoringStatus checkMethodInHierarchy(ITypeBinding type, String methodName, ITypeBinding returnType, ITypeBinding[] parameters) {
	RefactoringStatus result= new RefactoringStatus();
	IMethodBinding method= Bindings.findMethodInHierarchy(type, methodName, parameters);
	if (method != null) {
		boolean returnTypeClash= false;
		ITypeBinding methodReturnType= method.getReturnType();
		if (returnType != null && methodReturnType != null) {
			String returnTypeKey= returnType.getKey();
			String methodReturnTypeKey= methodReturnType.getKey();
			if (returnTypeKey == null && methodReturnTypeKey == null) {
				returnTypeClash= returnType != methodReturnType;
			} else if (returnTypeKey != null && methodReturnTypeKey != null) {
				returnTypeClash= !returnTypeKey.equals(methodReturnTypeKey);
			}
		}
		ITypeBinding dc= method.getDeclaringClass();
		if (returnTypeClash) {
			result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_returnTypeClash,
				new Object[] {BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName())}),
				JavaStatusContext.create(method));
		} else {
			if (method.isConstructor()) {
				result.addWarning(Messages.format(RefactoringCoreMessages.Checks_methodName_constructor,
						new Object[] { BasicElementLabels.getJavaElementName(dc.getName()) }));
			} else {
				result.addError(Messages.format(RefactoringCoreMessages.Checks_methodName_overrides,
						new Object[] { BasicElementLabels.getJavaElementName(methodName), BasicElementLabels.getJavaElementName(dc.getName()) }),
						JavaStatusContext.create(method));
			}
		}
	}
	return result;
}
 
Example 7
Source File: JsInteropUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static JsMemberType getJsMemberType(IBinding member, boolean isPropertyAccessor) {
  if (member instanceof IVariableBinding) {
    return JsMemberType.PROPERTY;
  }
  IMethodBinding method = (IMethodBinding) member;
  if (method.isConstructor()) {
    return JsMemberType.CONSTRUCTOR;
  }
  if (isPropertyAccessor) {
    return getJsPropertyAccessorType(method);
  }
  return JsMemberType.METHOD;
}
 
Example 8
Source File: MethodChecks.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns <code>true</code> iff the method could be a virtual method,
 * i.e. if it is not a constructor, is private, or is static.
 *
 * @param methodBinding a method
 * @return <code>true</code> iff the method could a virtual method
 */
public static boolean isVirtual(IMethodBinding methodBinding){
	if (methodBinding.isConstructor())
		return false;
	if (Modifier.isPrivate(methodBinding.getModifiers()))
		return false;
	if (Modifier.isStatic(methodBinding.getModifiers()))
		return false;
	return true;
}
 
Example 9
Source File: InferTypeArgumentsConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void endVisit(MethodDeclaration node) {
	IMethodBinding methodBinding= node.resolveBinding();

	if (methodBinding == null)
		return; //TODO: emit error?

	int parameterCount= node.parameters().size();
	ConstraintVariable2[] parameterTypeCvs= new ConstraintVariable2[parameterCount];
	for (int i= 0; i < parameterCount; i++) {
		SingleVariableDeclaration paramDecl= (SingleVariableDeclaration) node.parameters().get(i);
		//parameterTypeVariable currently not used, but need to register in order to store source range
		ConstraintVariable2 parameterTypeCv= fTCModel.makeDeclaredParameterTypeVariable(methodBinding, i, fCU);
		parameterTypeCvs[i]= parameterTypeCv;
		if (parameterTypeCv == null)
			continue;

		//creating equals constraint between parameterTypeVariable's elements and the Type's elements
		ConstraintVariable2 typeCv= getConstraintVariable(paramDecl.getType());
		fTCModel.createElementEqualsConstraints(parameterTypeCv, typeCv);

		//TODO: should avoid having a VariableVariable as well as a ParameterVariable for a parameter
		ConstraintVariable2 nameCv= getConstraintVariable(paramDecl.getName());
		fTCModel.createElementEqualsConstraints(parameterTypeCv, nameCv);
	}

	ConstraintVariable2 returnTypeCv= null;
	if (! methodBinding.isConstructor()) {
		//TODO: should only create return type variable if type is generic?
		ConstraintVariable2 returnTypeBindingCv= fTCModel.makeDeclaredReturnTypeVariable(methodBinding, fCU);
		if (returnTypeBindingCv != null) {
			returnTypeCv= getConstraintVariable(node.getReturnType2());
			fTCModel.createElementEqualsConstraints(returnTypeBindingCv, returnTypeCv);
		}
	}
	if (MethodChecks.isVirtual(methodBinding)) {
		//TODO: RippleMethod constraints for corner cases: see testCuRippleMethods3, bug 41989
		addConstraintsForOverriding(methodBinding, returnTypeCv, parameterTypeCvs);
	}
}
 
Example 10
Source File: SuperTypeConstraintsCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * 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);
	}
}
 
Example 11
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(MethodDeclaration declaration){
	List<ITypeConstraint> result= new ArrayList<ITypeConstraint>();
	IMethodBinding methodBinding= declaration.resolveBinding();
	if (methodBinding == null)
		return new ITypeConstraint[0];
	ITypeConstraint[] constraints = fTypeConstraintFactory.createDefinesConstraint(
			fConstraintVariableFactory.makeDeclaringTypeVariable(methodBinding),
			fConstraintVariableFactory.makeRawBindingVariable(methodBinding.getDeclaringClass()));
	result.addAll(Arrays.asList(constraints));
	if (! methodBinding.isConstructor() && ! methodBinding.getReturnType().isPrimitive()){
		ConstraintVariable returnTypeBindingVariable= fConstraintVariableFactory.makeReturnTypeVariable(methodBinding);
		ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeTypeVariable(declaration.getReturnType2());
		ITypeConstraint[] defines= fTypeConstraintFactory.createDefinesConstraint(
				returnTypeBindingVariable, returnTypeVariable);
		result.addAll(Arrays.asList(defines));
	}
	for (int i= 0, n= declaration.parameters().size(); i < n; i++) {
		SingleVariableDeclaration paramDecl= (SingleVariableDeclaration)declaration.parameters().get(i);
		ConstraintVariable parameterTypeVariable= fConstraintVariableFactory.makeParameterTypeVariable(methodBinding, i);
		ConstraintVariable parameterNameVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(paramDecl.getName(), getContext());
		ITypeConstraint[] constraint= fTypeConstraintFactory.createDefinesConstraint(
				parameterTypeVariable, parameterNameVariable);
		result.addAll(Arrays.asList(constraint));
	}
	if (MethodChecks.isVirtual(methodBinding)){
		Collection<ITypeConstraint> constraintsForOverriding = getConstraintsForOverriding(methodBinding);
		result.addAll(constraintsForOverriding);
	}
	return result.toArray(new ITypeConstraint[result.size()]);
}
 
Example 12
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static IBinding resolveSuperclassConstructor(ITypeBinding superClassDeclaration, IMethodBinding constructor) {
	IMethodBinding[] methods= superClassDeclaration.getDeclaredMethods();
	for (int i= 0; i < methods.length; i++) {
		IMethodBinding method= methods[i];
		if (method.isConstructor() && constructor.isSubsignature(method))
			return method;
	}
	return null;
}
 
Example 13
Source File: MethodChecks.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns <code>true</code> iff the method could be a virtual method,
 * i.e. if it is not a constructor, is private, or is static.
 *
 * @param methodBinding a method
 * @return <code>true</code> iff the method could a virtual method
 */
public static boolean isVirtual(IMethodBinding methodBinding){
	if (methodBinding.isConstructor()) {
		return false;
	}
	if (Modifier.isPrivate(methodBinding.getModifiers())) {
		return false;
	}
	if (Modifier.isStatic(methodBinding.getModifiers())) {
		return false;
	}
	return true;
}
 
Example 14
Source File: JDTUtils.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private static IBinding resolveSuperclassConstructor(ITypeBinding superClassDeclaration, IMethodBinding constructor) {
	IMethodBinding[] methods = superClassDeclaration.getDeclaredMethods();
	for (int i = 0; i < methods.length; i++) {
		IMethodBinding method = methods[i];
		if (method.isConstructor() && constructor.isSubsignature(method)) {
			return method;
		}
	}
	return null;
}
 
Example 15
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
ParameterNameInitializer createParameterNameInitializer(IMethodBinding method, WorkingCopyOwner workingCopyOwner,
		JvmExecutable result, String handleIdentifier, String[] path, String name, SegmentSequence signaturex) {
	if (method.isConstructor() && method.getDeclaringClass().isEnum()) {
		return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
	} else {
		return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
	}
}
 
Example 16
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private ITypeConstraint[] getReturnTypeConstraint(Expression invocation, IMethodBinding methodBinding){
	if (methodBinding == null || methodBinding.isConstructor() || methodBinding.getReturnType().isPrimitive())
		return new ITypeConstraint[0];
	ConstraintVariable returnTypeVariable= fConstraintVariableFactory.makeReturnTypeVariable(methodBinding);
	ConstraintVariable invocationVariable= fConstraintVariableFactory.makeExpressionOrTypeVariable(invocation, getContext());
	return fTypeConstraintFactory.createDefinesConstraint(invocationVariable, returnTypeVariable);
}
 
Example 17
Source File: JdtBasedTypeFactory.java    From xtext-eclipse with Eclipse Public License 2.0 5 votes vote down vote up
@Override
ParameterNameInitializer createParameterNameInitializer(
		IMethodBinding method,
		WorkingCopyOwner workingCopyOwner,
		JvmExecutable result,
		String handleIdentifier,
		String[] path,
		String name,
		SegmentSequence signaturex) {
	if (method.isConstructor()) {
		ITypeBinding declarator = method.getDeclaringClass();
		if (declarator.isEnum()) {
			return new EnumConstructorParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
		}
		if (declarator.isMember()) {
			return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex) {
				@Override
				protected void setParameterNames(IMethod javaMethod, java.util.List<JvmFormalParameter> parameters) throws JavaModelException {
					String[] parameterNames = javaMethod.getParameterNames();
					int size = parameters.size();
					if (size == parameterNames.length) {
						super.setParameterNames(javaMethod, parameters);
					} else if (size == parameterNames.length - 1) {
						for (int i = 1; i < parameterNames.length; i++) {
							String string = parameterNames[i];
							parameters.get(i - 1).setName(string);
						}
					} else {
						throw new IllegalStateException("unmatching arity for java method "+javaMethod.toString()+" and "+getExecutable().getIdentifier());
					}
				}
			};
		}
	}
	return new ParameterNameInitializer(workingCopyOwner, result, handleIdentifier, path, name, signaturex);
}
 
Example 18
Source File: JdtUtils.java    From j2cl with Apache License 2.0 5 votes vote down vote up
private static Set<IMethodBinding> getOverriddenMethodsInType(
    IMethodBinding methodBinding, ITypeBinding typeBinding) {
  Set<IMethodBinding> overriddenMethods = new HashSet<>();
  for (IMethodBinding declaredMethod : typeBinding.getDeclaredMethods()) {
    if (methodBinding.overrides(declaredMethod) && !methodBinding.isConstructor()) {
      checkArgument(!Modifier.isStatic(methodBinding.getModifiers()));
      overriddenMethods.add(declaredMethod);
    }
  }
  // Recurse into immediate super class and interfaces for overridden method.
  if (typeBinding.getSuperclass() != null) {
    overriddenMethods.addAll(
        getOverriddenMethodsInType(methodBinding, typeBinding.getSuperclass()));
  }
  for (ITypeBinding interfaceBinding : typeBinding.getInterfaces()) {
    overriddenMethods.addAll(getOverriddenMethodsInType(methodBinding, interfaceBinding));
  }

  ITypeBinding javaLangObjectTypeBinding = JdtUtils.javaLangObjectTypeBinding.get();
  if (typeBinding != javaLangObjectTypeBinding) {
    for (IMethodBinding objectMethodBinding : javaLangObjectTypeBinding.getDeclaredMethods()) {
      if (!isPolymorphic(objectMethodBinding)) {
        continue;
      }
      checkState(!getVisibility(objectMethodBinding).isPackagePrivate());
      if (methodBinding.isSubsignature(objectMethodBinding)) {
        overriddenMethods.add(objectMethodBinding);
      }
    }
  }

  return overriddenMethods;
}
 
Example 19
Source File: JdtUtils.java    From j2cl with Apache License 2.0 4 votes vote down vote up
private static boolean isPolymorphic(IMethodBinding methodBinding) {
  return !methodBinding.isConstructor()
      && !isStatic(methodBinding)
      && !Modifier.isPrivate(methodBinding.getModifiers());
}
 
Example 20
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();
}