下面列出了org.eclipse.jdt.core.dom.IMethodBinding#isConstructor ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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;
}
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();
}
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;
}
@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;
}
/**
* 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;
}
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;
}
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;
}
@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);
}
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);
}
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);
}
}
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;
}
/**
* 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;
}
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;
}
@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()]);
}
/**
* 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);
}
}
@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);
}
}
/**
* 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;
}
/**
* 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;
}
/** 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();
}
private static boolean isPolymorphic(IMethodBinding methodBinding) {
return !methodBinding.isConstructor()
&& !isStatic(methodBinding)
&& !Modifier.isPrivate(methodBinding.getModifiers());
}