private static String[] getParameterTypesAsStringArray(IMethod method) { Set<String> typeParameterNames = new HashSet<String>(); try { for (ITypeParameter param : method.getDeclaringType().getTypeParameters()) { typeParameterNames.add(param.getElementName()); } for (ITypeParameter param : method.getTypeParameters()) { typeParameterNames.add(param.getElementName()); } } catch (JavaModelException e) { } String[] parameterTypesAsString = new String[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { String parameterTypeString = Signature.getElementType(method.getParameterTypes()[i]); boolean isArray = !parameterTypeString.equals(method.getParameterTypes()[i]); String parameterType = resolveClassNameBySignature(parameterTypeString, method.getDeclaringType()); if (typeParameterNames.contains(parameterType)) { parameterTypesAsString[i] = Object.class.getName() + (isArray ? ClassUtils.ARRAY_SUFFIX : ""); } else { parameterTypesAsString[i] = parameterType + (isArray ? ClassUtils.ARRAY_SUFFIX : ""); } } return parameterTypesAsString; }
private void extractIMethod(IMethod method, boolean annotationElement) { try { StringBuilder fqnBuilder = new StringBuilder(fqnStack.peek()); if (method.isConstructor()) { fqnBuilder.append('.').append("<init>"); } else { fqnBuilder.append('.').append(method.getElementName()); } fqnBuilder.append('('); boolean first = true; for (String param : method.getParameterTypes()) { if (first) { first = false; } else { fqnBuilder.append(','); } String sig = typeSignatureToFqn(param); fqnBuilder.append(sig); } fqnBuilder.append(')'); String fqn = fqnBuilder.toString(); // Write the entity if (annotationElement) { entityWriter.writeAnnotationElement(fqn, method.getFlags(), path); } else if (method.isConstructor()) { entityWriter.writeConstructor(fqn, method.getFlags(), path); } else { entityWriter.writeMethod(fqn, method.getFlags(), path); } // Write the inside relation relationWriter.writeInside(fqn, fqnStack.peek(), path); // Write the returns relation relationWriter.writeReturns(fqn, typeSignatureToFqn(method.getReturnType()), path); // Write the receives relation String[] paramTypes = method.getParameterTypes(); for (int i = 0; i < paramTypes.length; i++) { localVariableWriter.writeClassParameter( "arg" + i, typeSignatureToFqn(paramTypes[i]), fqn, i, path); // relationWriter.writeReceives(fqn, typeSignatureToFqn(paramTypes[i]), "arg" + i, // i); } int pos = 0; for (ITypeParameter param : method.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } } catch (JavaModelException e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }
public static final List<IType> getJavaTypesForMethodParameterTypes( IMethod method, IType contextType) { if (method == null || method.getParameterTypes() == null || method.getParameterTypes().length == 0) { return Collections.EMPTY_LIST; } List<IType> parameterTypes = new ArrayList<IType>(method.getParameterTypes().length); String[] parameterTypeNames = method.getParameterTypes(); for (String parameterTypeName : parameterTypeNames) { parameterTypes.add( JdtUtils.getJavaTypeFromSignatureClassName(parameterTypeName, contextType)); } return parameterTypes; }
static final IMethod[] hierarchyDeclaresMethodName( IProgressMonitor pm, ITypeHierarchy hierarchy, IMethod method, String newName) throws CoreException { try { Set<IMethod> result = new HashSet<>(); IType type = method.getDeclaringType(); IMethod foundMethod = Checks.findMethod(newName, method.getParameterTypes().length, false, type); if (foundMethod != null) result.add(foundMethod); IMethod[] foundInHierarchyClasses = classesDeclareMethodName( hierarchy, Arrays.asList(hierarchy.getAllClasses()), method, newName); if (foundInHierarchyClasses != null) result.addAll(Arrays.asList(foundInHierarchyClasses)); IType[] implementingClasses = hierarchy.getImplementingClasses(type); IMethod[] foundInImplementingClasses = classesDeclareMethodName(hierarchy, Arrays.asList(implementingClasses), method, newName); if (foundInImplementingClasses != null) result.addAll(Arrays.asList(foundInImplementingClasses)); return result.toArray(new IMethod[result.size()]); } finally { if (pm != null) { pm.done(); } } }
/** * Gets the fully qualified name of the supplied java element. * * <p>NOTE: For easy of determining fields and method segments, they are appended with a javadoc * style '#' instead of the normal '.'. * * @param element The IJavaElement. * @return The fully qualified name. */ public static String getFullyQualifiedName(IJavaElement element) { IJavaElement parent = element; while (parent.getElementType() != IJavaElement.COMPILATION_UNIT && parent.getElementType() != IJavaElement.CLASS_FILE) { parent = parent.getParent(); } StringBuffer elementName = new StringBuffer() .append(parent.getParent().getElementName()) .append('.') .append(FileUtils.getFileName(parent.getElementName())); switch (element.getElementType()) { case IJavaElement.FIELD: IField field = (IField) element; elementName.append('#').append(field.getElementName()); break; case IJavaElement.METHOD: IMethod method = (IMethod) element; elementName.append('#').append(method.getElementName()).append('('); String[] parameters = method.getParameterTypes(); for (int ii = 0; ii < parameters.length; ii++) { if (ii != 0) { elementName.append(", "); } elementName.append(Signature.toString(parameters[ii]).replace('/', '.')); } elementName.append(')'); break; } return elementName.toString(); }
/** @since 3.2.0 */ public static IMethod getMethod( IType type, String methodName, String[] parameterTypes, boolean includeHierarchy) { int index = methodName.indexOf('('); if (index >= 0) { methodName = methodName.substring(0, index); } try { while (type != null) { for (IMethod method : Introspector.getMethods(type)) { if (method.getElementName().equals(methodName) && method.getParameterTypes().length == parameterTypes.length) { String[] methodParameterTypes = getParameterTypesAsStringArray(method); if (Arrays.deepEquals(parameterTypes, methodParameterTypes)) { return method; } } } if (!includeHierarchy) break; type = Introspector.getSuperType(type); } return Introspector.findMethod( type, methodName, parameterTypes.length, Public.YES, Static.DONT_CARE); } catch (JavaModelException e) { } return null; }
public ITypeModel getBodyType() { IMethod iMethod = (IMethod) tm; try { String[] parameterTypes = iMethod.getParameterTypes(); for (String s : parameterTypes) { if (s.contains("java")) // $NON-NLS-1$ { continue; } String returnType = s; if (returnType.startsWith("Q") && returnType.endsWith(";")) { // $NON-NLS-1$ //$NON-NLS-2$ IType ownerType = (IType) iMethod.getAncestor(IJavaElement.TYPE); String[][] resolveType = ownerType.resolveType(returnType.substring(1, returnType.length() - 1)); if (resolveType.length == 1) { IType findType = ownerType.getJavaProject().findType(resolveType[0][0] + '.' + resolveType[0][1]); if (findType != null && findType instanceof SourceType) { return new JDTType(findType); } } } } } catch (Exception e) { throw new IllegalStateException(e); } return null; }
/** * Finds a method in a list of methods. Compares methods by signature (only SimpleNames of types), * and not by the declaring type. * * @param method the method to find * @param allMethods the methods to look at * @return The found method or <code>null</code>, if nothing found * @throws JavaModelException */ public static IMethod findMethod(IMethod method, IMethod[] allMethods) throws JavaModelException { String name = method.getElementName(); String[] paramTypes = method.getParameterTypes(); boolean isConstructor = method.isConstructor(); for (int i = 0; i < allMethods.length; i++) { if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, allMethods[i])) return allMethods[i]; } return null; }
public static IMethod getConstructor(IType type, String[] parameterTypes) { try { Set<IMethod> methods = Introspector.getAllConstructors(type); for (IMethod method : methods) { if (method.getParameterTypes().length == parameterTypes.length) { String[] methodParameterTypes = getParameterTypesAsStringArray(method); if (Arrays.deepEquals(parameterTypes, methodParameterTypes)) { return method; } } } } catch (JavaModelException e) { } return null; }
/** @return true if the method is static has two parameters namely a DispatchContext and a map */ private static boolean isOfbizService(IMethod method) throws JavaModelException { if (isStatic(method) && isPublic(method)) { String[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 2 && paramTypes[0].equals("QDispatchContext;") && (paramTypes[1].equals("QMap<QString;QObject;>;") || paramTypes[1].equals("QMap<QString;+QObject;>;") || paramTypes[1].equals("QMap<QString;*>;") || paramTypes[1].equals("QMap;"))) { return true; } } return false; }
public static IMethod[] findMethods( IMethod[] selectedMethods, String[] namesOfMethods, String[][] signaturesOfMethods) { List found = new ArrayList(selectedMethods.length); for (int i = 0; i < selectedMethods.length; i++) { IMethod method = selectedMethods[i]; String[] paramTypes = method.getParameterTypes(); for (int j = 0; j < namesOfMethods.length; j++) { String methodName = namesOfMethods[j]; if (!methodName.equals(method.getElementName())) continue; String[] methodSig = signaturesOfMethods[j]; if (!areSameSignatures(paramTypes, methodSig)) continue; found.add(method); } } return (IMethod[]) found.toArray(new IMethod[found.size()]); }
private String toSignature(IMethod method) { StringBuilder result = new StringBuilder(method.getElementName()); String[] types = method.getParameterTypes(); try { String[] names = method.getParameterNames(); result.append("("); for (int i = 0; i < types.length; i++) { if (i > 0) result.append(", "); result.append(Signature.toString(types[i]) + " " + names[i]); } result.append(")"); } catch (JavaModelException ex) { // ignore } return result.toString(); }
public String convertToString(Object parameterValue) throws ParameterValueConversionException { if (!(parameterValue instanceof IJavaElement)) { throw new ParameterValueConversionException( "parameterValue must be an IJavaElement"); //$NON-NLS-1$ } IJavaElement javaElement = (IJavaElement) parameterValue; IJavaProject javaProject = javaElement.getJavaProject(); if (javaProject == null) { throw new ParameterValueConversionException( "Could not get IJavaProject for element"); //$NON-NLS-1$ } StringBuffer buffer; if (javaElement instanceof IType) { IType type = (IType) javaElement; buffer = composeTypeReference(type); } else if (javaElement instanceof IMethod) { IMethod method = (IMethod) javaElement; buffer = composeTypeReference(method.getDeclaringType()); buffer.append(TYPE_END_CHAR); buffer.append(method.getElementName()); String[] parameterTypes = method.getParameterTypes(); buffer.append(PARAM_START_CHAR); for (int i = 0; i < parameterTypes.length; i++) { buffer.append(parameterTypes[i]); } buffer.append(PARAM_END_CHAR); } else if (javaElement instanceof IField) { IField field = (IField) javaElement; buffer = composeTypeReference(field.getDeclaringType()); buffer.append(TYPE_END_CHAR); buffer.append(field.getElementName()); } else { throw new ParameterValueConversionException("Unsupported IJavaElement type"); // $NON-NLS-1$ } return buffer.toString(); }
private static void appendMethodReference(IMethod meth, StringBuffer buf) throws JavaModelException { buf.append(meth.getElementName()); /* * The Javadoc tool for Java SE 8 changed the anchor syntax and now tries to avoid "strange" characters in URLs. * This breaks all clients that directly create such URLs. * We can't know what format is required, so we just guess by the project's compiler compliance. */ boolean is18OrHigher = JavaModelUtil.is18OrHigher(meth.getJavaProject()); buf.append(is18OrHigher ? '-' : '('); String[] params = meth.getParameterTypes(); IType declaringType = meth.getDeclaringType(); boolean isVararg = Flags.isVarargs(meth.getFlags()); int lastParam = params.length - 1; for (int i = 0; i <= lastParam; i++) { if (i != 0) { buf.append(is18OrHigher ? "-" : ", "); // $NON-NLS-1$ //$NON-NLS-2$ } String curr = Signature.getTypeErasure(params[i]); String fullName = JavaModelUtil.getResolvedTypeName(curr, declaringType); if (fullName == null) { // e.g. a type parameter "QE;" fullName = Signature.toString(Signature.getElementType(curr)); } if (fullName != null) { buf.append(fullName); int dim = Signature.getArrayCount(curr); if (i == lastParam && isVararg) { dim--; } while (dim > 0) { buf.append(is18OrHigher ? ":A" : "[]"); // $NON-NLS-1$ //$NON-NLS-2$ dim--; } if (i == lastParam && isVararg) { buf.append("..."); // $NON-NLS-1$ } } } buf.append(is18OrHigher ? '-' : ')'); }
private RefactoringStatus checkNewAccessor(IMethod existingAccessor, String newAccessorName) throws CoreException { RefactoringStatus result = new RefactoringStatus(); IMethod accessor = JavaModelUtil.findMethod( newAccessorName, existingAccessor.getParameterTypes(), false, fField.getDeclaringType()); if (accessor == null || !accessor.exists()) return null; String message = Messages.format( RefactoringCoreMessages.RenameFieldRefactoring_already_exists, new String[] { JavaElementUtil.createMethodSignature(accessor), BasicElementLabels.getJavaElementName( fField.getDeclaringType().getFullyQualifiedName('.')) }); result.addError(message, JavaStatusContext.create(accessor)); return result; }
// ------- private static IMethod[] classesDeclareMethodName( ITypeHierarchy hier, List<IType> classes, IMethod method, String newName) throws CoreException { Set<IMethod> result = new HashSet<>(); IType type = method.getDeclaringType(); List<IType> subtypes = Arrays.asList(hier.getAllSubtypes(type)); int parameterCount = method.getParameterTypes().length; boolean isMethodPrivate = JdtFlags.isPrivate(method); for (Iterator<IType> iter = classes.iterator(); iter.hasNext(); ) { IType clazz = iter.next(); IMethod[] methods = clazz.getMethods(); boolean isSubclass = subtypes.contains(clazz); for (int j = 0; j < methods.length; j++) { IMethod foundMethod = Checks.findMethod(newName, parameterCount, false, new IMethod[] {methods[j]}); if (foundMethod == null) continue; if (isSubclass || type.equals(clazz)) result.add(foundMethod); else if ((!isMethodPrivate) && (!JdtFlags.isPrivate(methods[j]))) result.add(foundMethod); } } return result.toArray(new IMethod[result.size()]); }
/** * Determines whether the given member is a valid android.view.View to be added to the list of * custom views or third party views. It checks that the view is public and not abstract for * example. */ private static boolean isValidView(IType type, boolean layoutsOnly) throws JavaModelException { // Skip anonymous classes if (type.isAnonymous()) { return false; } int flags = type.getFlags(); if (Flags.isAbstract(flags) || !Flags.isPublic(flags)) { return false; } // TODO: if (layoutsOnly) perhaps try to filter out AdapterViews and other ViewGroups // not willing to accept children via XML // See if the class has one of the acceptable constructors // needed for XML instantiation: // View(Context context) // View(Context context, AttributeSet attrs) // View(Context context, AttributeSet attrs, int defStyle) // We don't simply do three direct checks via type.getMethod() because the types // are not resolved, so we don't know for each parameter if we will get the // fully qualified or the unqualified class names. // Instead, iterate over the methods and look for a match. String typeName = type.getElementName(); for (IMethod method : type.getMethods()) { // Only care about constructors if (!method.getElementName().equals(typeName)) { continue; } String[] parameterTypes = method.getParameterTypes(); if (parameterTypes == null || parameterTypes.length < 1 || parameterTypes.length > 3) { continue; } String first = parameterTypes[0]; // Look for the parameter type signatures -- produced by // JDT's Signature.createTypeSignature("Context", false /*isResolved*/);. // This is not a typo; they were copy/pasted from the actual parameter names // observed in the debugger examining these data structures. if (first.equals("QContext;") // $NON-NLS-1$ || first.equals("Qandroid.content.Context;")) { // $NON-NLS-1$ if (parameterTypes.length == 1) { return true; } String second = parameterTypes[1]; if (second.equals("QAttributeSet;") // $NON-NLS-1$ || second.equals("Qandroid.util.AttributeSet;")) { // $NON-NLS-1$ if (parameterTypes.length == 2) { return true; } String third = parameterTypes[2]; if (third.equals("I")) { // $NON-NLS-1$ if (parameterTypes.length == 3) { return true; } } } } } return false; }
@Override public Object getNewElement() { return fMethod.getDeclaringType().getMethod(getNewElementName(), fMethod.getParameterTypes()); }
private IMethod getMethodInWorkingCopy(IMethod method, String elementName, IType typeWc) { String[] paramTypeSignatures = method.getParameterTypes(); return typeWc.getMethod(elementName, paramTypeSignatures); }
@Override public List<ICompletionProposal> computeCompletionProposals( final ContentAssistInvocationContext context, final IProgressMonitor monitor) { final List<ICompletionProposal> list = new ArrayList<ICompletionProposal>(); boolean extendContext = false; try { if (context instanceof JavaContentAssistInvocationContext) { final ITextViewer viewer = context.getViewer(); final List<ScriptVariable> scriptVariables = getScriptVariables(viewer); if (scriptVariables.isEmpty()) { return list; } final CompletionContext coreContext = ((JavaContentAssistInvocationContext) context).getCoreContext(); if (coreContext != null && !coreContext.isExtended()) { // must use reflection to set the fields ReflectionUtils.setPrivateField( InternalCompletionContext.class, "isExtended", coreContext, true); extendContext = true; } final ICompilationUnit unit = ((JavaContentAssistInvocationContext) context).getCompilationUnit(); if (unit instanceof GroovyCompilationUnit) { if (((GroovyCompilationUnit) unit).getModuleNode() == null) { return Collections.emptyList(); } final ContentAssistContext assistContext = new GroovyCompletionProposalComputer() .createContentAssistContext( (GroovyCompilationUnit) unit, context.getInvocationOffset(), context.getDocument()); CharSequence prefix = null; try { prefix = context.computeIdentifierPrefix(); } catch (final BadLocationException e) { BonitaStudioLog.error(e); } if (assistContext != null && assistContext.completionNode instanceof VariableExpression) { try { final VariableExpression expr = (VariableExpression) assistContext.completionNode; if (scriptVariables != null) { for (final ScriptVariable f : scriptVariables) { if (expr.getName().equals(f.getName())) { final IType type = javaProject.findType(f.getType()); if (type == null) { return list; } for (final IMethod m : type.getMethods()) { if (m.getElementName().startsWith(prefix.toString())) { final GroovyCompletionProposal proposal = new GroovyCompletionProposal( CompletionProposal.METHOD_REF, context.getInvocationOffset()); proposal.setName(m.getElementName().toCharArray()); proposal.setCompletion( m.getElementName().substring(prefix.length()).toCharArray()); proposal.setFlags(m.getFlags()); if (prefix.length() == m.getElementName().length()) { proposal.setReplaceRange( context.getInvocationOffset(), context.getInvocationOffset()); proposal.setReceiverRange(0, 0); } else { proposal.setReplaceRange( context.getInvocationOffset() - prefix.length(), context.getInvocationOffset()); proposal.setReceiverRange(prefix.length(), prefix.length()); } final char[][] parametersArray = new char[m.getParameterNames().length][256]; final List<Parameter> parameters = new ArrayList<Parameter>(); for (int i = 0; i < m.getParameterNames().length; i++) { parametersArray[i] = m.getParameterNames()[i].toCharArray(); parameters.add( new Parameter( ClassHelper.make( Signature.getSignatureSimpleName(m.getParameterTypes()[i])), m.getParameterNames()[i])); } final ClassNode classNode = ClassHelper.make(m.getDeclaringType().getFullyQualifiedName()); proposal.setDeclarationSignature( ProposalUtils.createTypeSignature(classNode)); proposal.setParameterNames(parametersArray); if (m.getDeclaringType().getFullyQualifiedName().equals(f.getType())) { proposal.setRelevance(100); } final MethodNode methodNode = new MethodNode( m.getElementName(), m.getFlags(), ClassHelper.make( Signature.getSignatureSimpleName(m.getReturnType())), parameters.toArray(new Parameter[parameters.size()]), new ClassNode[0], null); final char[] methodSignature = ProposalUtils.createMethodSignature(methodNode); proposal.setSignature(methodSignature); final GroovyJavaGuessingCompletionProposal groovyProposal = GroovyJavaGuessingCompletionProposal.createProposal( proposal, (JavaContentAssistInvocationContext) context, true, "Groovy", ProposalFormattingOptions.newFromOptions()); if (groovyProposal != null) { list.add(groovyProposal); } } } } } } } catch (final JavaModelException e) { BonitaStudioLog.error(e); } } } return list; } } finally { final CompletionContext coreContext = ((JavaContentAssistInvocationContext) context).getCoreContext(); if (extendContext && coreContext != null && coreContext.isExtended()) { // must use reflection to set the fields ReflectionUtils.setPrivateField( InternalCompletionContext.class, "isExtended", coreContext, false); } } return Collections.emptyList(); }
private void extractIType(IType type) { try { String fqn = type.getFullyQualifiedName(); // Write the entity if (type.isClass()) { entityWriter.writeClass(fqn, type.getFlags(), path); // Write the superclass String superSig = type.getSuperclassTypeSignature(); if (superSig != null) { relationWriter.writeExtends(fqn, typeSignatureToFqn(superSig), path); } } else if (type.isAnnotation()) { entityWriter.writeAnnotation(fqn, type.getFlags(), path); } else if (type.isInterface()) { entityWriter.writeInterface(fqn, type.getFlags(), path); } else if (type.isEnum()) { entityWriter.writeEnum(fqn, type.getFlags(), path); } // Write the superinterfaces for (String superIntSig : type.getSuperInterfaceTypeSignatures()) { relationWriter.writeImplements(fqn, typeSignatureToFqn(superIntSig), path); } if (!fqnStack.isEmpty()) { relationWriter.writeInside(type.getFullyQualifiedName(), fqnStack.peek(), path); } fqnStack.push(type.getFullyQualifiedName()); for (IType child : type.getTypes()) { extractIType(child); } for (IField field : type.getFields()) { if (!Flags.isSynthetic(field.getFlags())) { extractIField(field); } } for (IMethod method : type.getMethods()) { if (!Flags.isSynthetic(method.getFlags()) || (Flags.isSynthetic(method.getFlags()) && method.isConstructor() && method.getParameterTypes().length == 0)) { extractIMethod(method, type.isAnnotation()); } } int pos = 0; for (ITypeParameter param : type.getTypeParameters()) { relationWriter.writeParametrizedBy(fqn, getTypeParam(param), pos++, path); } fqnStack.pop(); } catch (Exception e) { logger.log(Level.SEVERE, "Error in extracting class file", e); } }
private String createParamCountKey(final IMethod method) { return method.getElementName() + "@" + method.getParameterTypes().length; // $NON-NLS-1$ }