/** * Tries to find the given {@link IApiMethod} in the given {@link IType}. If a matching method is * not found <code>null</code> is returned * * @param type the type top look in for the given {@link IApiMethod} * @param method the {@link IApiMethod} to look for * @return the {@link IMethod} from the given {@link IType} that matches the given {@link * IApiMethod} or <code>null</code> if no matching method is found * @throws JavaModelException * @throws CoreException */ protected IMethod findMethodInType(IType type, IApiMethod method) throws JavaModelException, CoreException { String[] parameterTypes = Signature.getParameterTypes(method.getSignature()); for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = parameterTypes[i].replace('/', '.'); } String methodname = method.getName(); if (method.isConstructor()) { IApiType enclosingType = method.getEnclosingType(); if (enclosingType.isMemberType() && !Flags.isStatic(enclosingType.getModifiers())) { // remove the synthetic argument that corresponds to the enclosing type int length = parameterTypes.length - 1; System.arraycopy(parameterTypes, 1, (parameterTypes = new String[length]), 0, length); } methodname = enclosingType.getSimpleName(); } IMethod Qmethod = type.getMethod(methodname, parameterTypes); IMethod[] methods = type.getMethods(); IMethod match = null; for (int i = 0; i < methods.length; i++) { IMethod m = methods[i]; if (m.isSimilar(Qmethod)) { match = m; break; } } return match; }
public Object convertToObject(String parameterValue) throws ParameterValueConversionException { assertWellFormed(parameterValue != null); final int projectEndPosition = parameterValue.indexOf(PROJECT_END_CHAR); assertWellFormed(projectEndPosition != -1); String projectName = parameterValue.substring(0, projectEndPosition); String javaElementRef = parameterValue.substring(projectEndPosition + 1); IJavaModel javaModel = JavaCore.create(ResourcesPlugin.getWorkspace().getRoot()); assertExists(javaModel); IJavaProject javaProject = javaModel.getJavaProject(projectName); assertExists(javaProject); final int typeEndPosition = javaElementRef.indexOf(TYPE_END_CHAR); String typeName; if (typeEndPosition == -1) { typeName = javaElementRef; } else { typeName = javaElementRef.substring(0, typeEndPosition); } IType type = null; try { type = javaProject.findType(typeName); } catch (JavaModelException ex) { // type == null } assertExists(type); if (typeEndPosition == -1) { return type; } String memberRef = javaElementRef.substring(typeEndPosition + 1); final int paramStartPosition = memberRef.indexOf(PARAM_START_CHAR); if (paramStartPosition == -1) { IField field = type.getField(memberRef); assertExists(field); return field; } String methodName = memberRef.substring(0, paramStartPosition); String signature = memberRef.substring(paramStartPosition); String[] parameterTypes = null; try { parameterTypes = Signature.getParameterTypes(signature); } catch (IllegalArgumentException ex) { // parameterTypes == null } assertWellFormed(parameterTypes != null); IMethod method = type.getMethod(methodName, parameterTypes); assertExists(method); return method; }
public static IMethod[] getMethods(IType type, String[] names, String[][] signatures) { if (names == null || signatures == null) return new IMethod[0]; List methods = new ArrayList(names.length); for (int i = 0; i < names.length; i++) { IMethod method = type.getMethod(names[i], signatures[i]); assertTrue("method " + method.getElementName() + " does not exist", method.exists()); if (!methods.contains(method)) methods.add(method); } return (IMethod[]) methods.toArray(new IMethod[methods.size()]); }
private Set<IMethod> getExcludedMethods( IType objectClass, LinkedHashSet<MethodSkeleton<U>> methodSkeletons) throws Exception { Set<IMethod> excludedMethods = new HashSet<IMethod>(); for (MethodSkeleton<U> methodSkeleton : methodSkeletons) { IMethod excludedMethod = objectClass.getMethod( methodSkeleton.getMethodName(), methodSkeleton.getMethodArguments(objectClass)); if (excludedMethod.exists()) { excludedMethods.add(excludedMethod); } } return excludedMethods; }
public void testCustomPreferences() throws Exception { DiaGenSource s = createLibraryGen(false); final GenDiagram gd = s.getGenDiagram(); GenCustomPreferencePage pp = GMFGenFactory.eINSTANCE.createGenCustomPreferencePage(); if (gd.getPreferencePages().isEmpty()) { gd.getPreferencePages().add(pp); } else { gd.getPreferencePages().get(0).getChildren().add(pp); } pp.setGenerateBoilerplate(true); pp.setName("Page Name"); pp.setQualifiedClassName( gd.getEditorGen().getEditor().getPackageName() + ".CustomPreferencePage"); GenPreference p1 = GMFGenFactory.eINSTANCE.createGenPreference(); p1.setName("PREF_XXX_ONE"); p1.setDefaultValue("\"XXX_ONE_DEFAULT\""); GenPreference p2 = GMFGenFactory.eINSTANCE.createGenPreference(); p2.setName("NO_PREFIX_XXX_TWO"); p2.setKey("KEY.XXX.TWO"); pp.getPreferences().add(p1); pp.getPreferences().add(p2); // generateAndCompile(s); // IProject generatedProject = ResourcesPlugin.getWorkspace().getRoot().getProject(gd.getEditorGen().getPlugin().getID()); IFile file_pp = generatedProject.getFile("/src/" + pp.getQualifiedClassName().replace('.', '/') + ".java"); assertTrue(file_pp.exists()); ICompilationUnit cuPage = (ICompilationUnit) JavaCore.create(file_pp); assertNotNull(cuPage); IType mainClass = cuPage.getTypes()[0]; assertNotNull(mainClass); assertEquals(2, mainClass.getFields().length); final IField p1field = mainClass.getField(p1.getName()); final IField p2field = mainClass.getField(p2.getName()); assertTrue(Flags.isPublic(p1field.getFlags())); assertTrue(Flags.isStatic(p1field.getFlags())); assertTrue(Flags.isPublic(p2field.getFlags())); assertTrue(Flags.isStatic(p2field.getFlags())); assertEquals('"' + p1.getKey() + '"', p1field.getConstant()); assertEquals('"' + p2.getKey() + '"', p2field.getConstant()); IMethod initMethod = mainClass.getMethod( "initDefaults", new String[] {"Q" + IPreferenceStore.class.getSimpleName() + ";"}); assertNotNull(initMethod); String methodText = initMethod.getSource(); assertTrue(methodText.indexOf(p1.getName()) != -1); assertTrue(methodText.indexOf(p1.getDefaultValue()) != -1); assertTrue(methodText.indexOf(p2.getName()) == -1); }
/** * Determines is the java element contains a specific method. * * <p>The syntax for the property tester is of the form: methodname, signature, modifiers. * * <ol> * <li>methodname - case sensitive method name, required. For example, <code>toString</code>. * <li>signature - JLS style method signature, required. For example, <code>(QString;)V</code>. * <li>modifiers - optional space separated list of modifiers, for example, <code>public static * </code>. * </ol> * * @param element the element to check for the method * @param args first arg is method name, secondary args are parameter types signatures * @return true if the method is found in the element, false otherwise */ private boolean hasMethod(IJavaElement element, Object[] args) { try { if (args.length > 1) { IType type = getType(element); if (type != null && type.exists()) { String name = (String) args[0]; String signature = (String) args[1]; String[] parms = Signature.getParameterTypes(signature); String returnType = Signature.getReturnType(signature); IMethod candidate = type.getMethod(name, parms); if (candidate.exists()) { // check return type if (candidate.getReturnType().equals(returnType)) { // check modifiers if (args.length > 2) { String modifierText = (String) args[2]; String[] modifiers = modifierText.split(" "); // $NON-NLS-1$ int flags = 0; for (int j = 0; j < modifiers.length; j++) { String modifier = modifiers[j]; Integer flag = (Integer) fgModifiers.get(modifier); if (flag != null) { flags = flags | flag.intValue(); } } if (candidate.getFlags() == flags) { return true; } } } } } } } catch (JavaModelException e) { } return false; }
/** * Returns the activity associated with the given layout file. * * <p>This is an alternative to {@link #guessActivity(IFile, String)}. Whereas guessActivity * simply looks for references to "R.layout.foo", this method searches for all usages of * Activity#setContentView(int), and for each match it looks up the corresponding call text (such * as "setContentView(R.layout.foo)"). From this it uses a regexp to pull out "foo" from this, and * stores the association that layout "foo" is associated with the activity class that contained * the setContentView call. * * <p>This has two potential advantages: * * <ol> * <li>It can be faster. We do the reference search -once-, and we've built a map of all the * layout-to-activity mappings which we can then immediately look up other layouts for, * which is particularly useful at startup when we have to compute the layout activity * associations to populate the theme choosers. * <li>It can be more accurate. Just because an activity references an "R.layout.foo" field * doesn't mean it's setting it as a content view. * </ol> * * However, this second advantage is also its chief problem. There are some common code constructs * which means that the associated layout is not explicitly referenced in a direct setContentView * call; on a couple of sample projects I tested I found patterns like for example * "setContentView(v)" where "v" had been computed earlier. Therefore, for now we're going to * stick with the more general approach of just looking up each field when needed. We're keeping * the code around, though statically compiled out with the "if (false)" construct below in case * we revisit this. * * @param layoutFile the layout whose activity we want to look up * @return the activity name */ @SuppressWarnings("all") @Nullable public String guessActivityBySetContentView(String layoutName) { if (false) { // These should be fields final Pattern LAYOUT_FIELD_PATTERN = Pattern.compile("R\\.layout\\.([a-z0-9_]+)"); // $NON-NLS-1$ Map<String, String> mUsages = null; sync(); if (mUsages == null) { final Map<String, String> usages = new HashMap<String, String>(); mUsages = usages; SearchRequestor requestor = new SearchRequestor() { @Override public void acceptSearchMatch(SearchMatch match) throws CoreException { Object element = match.getElement(); if (element instanceof IMethod) { IMethod method = (IMethod) element; IType declaringType = method.getDeclaringType(); String fqcn = declaringType.getFullyQualifiedName(); IDocumentProvider provider = new TextFileDocumentProvider(); IResource resource = match.getResource(); try { provider.connect(resource); IDocument document = provider.getDocument(resource); if (document != null) { String matchText = document.get(match.getOffset(), match.getLength()); Matcher matcher = LAYOUT_FIELD_PATTERN.matcher(matchText); if (matcher.find()) { usages.put(matcher.group(1), fqcn); } } } catch (Exception e) { AdtPlugin.log(e, "Can't find range information for %1$s", resource.getName()); } finally { provider.disconnect(resource); } } } }; try { IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject); if (javaProject == null) { return null; } // Search for which java classes call setContentView(R.layout.layoutname); String typeFqcn = "R.layout"; // $NON-NLS-1$ if (mPackage != null) { typeFqcn = mPackage + '.' + typeFqcn; } IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY); if (activityType != null) { IMethod method = activityType.getMethod( "setContentView", new String[] {"I"}); // $NON-NLS-1$ //$NON-NLS-2$ if (method.exists()) { SearchPattern pattern = SearchPattern.createPattern(method, REFERENCES); search(requestor, javaProject, pattern); } } } catch (CoreException e) { AdtPlugin.log(e, null); } } return mUsages.get(layoutName); } return null; }
protected void reportDeclaration( MethodBinding methodBinding, MatchLocator locator, SimpleSet knownMethods) throws CoreException { ReferenceBinding declaringClass = methodBinding.declaringClass; IType type = locator.lookupType(declaringClass); if (type == null) return; // case of a secondary type // Report match for binary if (type.isBinary()) { IMethod method = null; TypeBinding[] parameters = methodBinding.original().parameters; int parameterLength = parameters.length; char[][] parameterTypes = new char[parameterLength][]; for (int i = 0; i < parameterLength; i++) { char[] typeName = parameters[i].qualifiedSourceName(); for (int j = 0, dim = parameters[i].dimensions(); j < dim; j++) { typeName = CharOperation.concat(typeName, new char[] {'[', ']'}); } parameterTypes[i] = typeName; } method = locator.createBinaryMethodHandle(type, methodBinding.selector, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; IResource resource = type.getResource(); if (resource == null) resource = type.getJavaProject().getProject(); IBinaryType info = locator.getBinaryInfo( (org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource); locator.reportBinaryMemberDeclaration( resource, method, methodBinding, info, SearchMatch.A_ACCURATE); return; } // When source is available, report match if method is found in the declaring type IResource resource = type.getResource(); if (declaringClass instanceof ParameterizedTypeBinding) declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType(); ClassScope scope = ((SourceTypeBinding) declaringClass).scope; if (scope != null) { TypeDeclaration typeDecl = scope.referenceContext; AbstractMethodDeclaration methodDecl = typeDecl.declarationOf(methodBinding.original()); if (methodDecl != null) { // Create method handle from method declaration String methodName = new String(methodBinding.selector); Argument[] arguments = methodDecl.arguments; int length = arguments == null ? 0 : arguments.length; String[] parameterTypes = new String[length]; for (int i = 0; i < length; i++) { char[][] typeName = arguments[i].type.getParameterizedTypeName(); parameterTypes[i] = Signature.createTypeSignature(CharOperation.concatWith(typeName, '.'), false); } IMethod method = type.getMethod(methodName, parameterTypes); if (method == null || knownMethods.addIfNotIncluded(method) == null) return; // Create and report corresponding match int offset = methodDecl.sourceStart; this.match = new MethodDeclarationMatch( method, SearchMatch.A_ACCURATE, offset, methodDecl.sourceEnd - offset + 1, locator.getParticipant(), resource); locator.report(this.match); } } }
/** @see net.sf.commonclipse.Generator#getExistingMethod(org.eclipse.jdt.core.IType) */ @Override protected IMethod getExistingMethod(IType type) { return type.getMethod(getMethodName(), new String[] {"QObject;"}); // $NON-NLS-1$ }
private JavaElement getUnresolvedJavaElement() { IType declaringType = (IType) getDeclaringClass().getJavaElement(); if (declaringType == null) return null; if (!(this.resolver instanceof DefaultBindingResolver)) return null; ASTNode node = (ASTNode) ((DefaultBindingResolver) this.resolver).bindingsToAstNodes.get(this); if (node != null && declaringType.getParent().getElementType() != IJavaElement.CLASS_FILE) { if (node instanceof MethodDeclaration) { MethodDeclaration methodDeclaration = (MethodDeclaration) node; ArrayList parameterSignatures = new ArrayList(); Iterator iterator = methodDeclaration.parameters().iterator(); while (iterator.hasNext()) { SingleVariableDeclaration parameter = (SingleVariableDeclaration) iterator.next(); Type type = parameter.getType(); String typeSig = Util.getSignature(type); int arrayDim = parameter.getExtraDimensions(); if (parameter.getAST().apiLevel() >= AST.JLS3 && parameter.isVarargs()) { arrayDim++; } if (arrayDim > 0) { typeSig = Signature.createArraySignature(typeSig, arrayDim); } parameterSignatures.add(typeSig); } int parameterCount = parameterSignatures.size(); String[] parameters = new String[parameterCount]; parameterSignatures.toArray(parameters); return (JavaElement) declaringType.getMethod(getName(), parameters); } else { // annotation type member declaration AnnotationTypeMemberDeclaration typeMemberDeclaration = (AnnotationTypeMemberDeclaration) node; return (JavaElement) declaringType.getMethod( typeMemberDeclaration.getName().getIdentifier(), new String[0]); // annotation type members don't have parameters } } else { // case of method not in the created AST, or a binary method org.eclipse.jdt.internal.compiler.lookup.MethodBinding original = this.binding.original(); String selector = original.isConstructor() ? declaringType.getElementName() : new String(original.selector); TypeBinding[] parameters = original.parameters; int length = parameters == null ? 0 : parameters.length; String[] parameterSignatures = new String[length]; for (int i = 0; i < length; i++) { parameterSignatures[i] = new String(parameters[i].genericTypeSignature()).replace('/', '.'); } IMethod result = declaringType.getMethod(selector, parameterSignatures); if (declaringType.isBinary()) return (JavaElement) result; IMethod[] methods = null; try { methods = declaringType.getMethods(); } catch (JavaModelException e) { // declaring type doesn't exist return null; } IMethod[] candidates = Member.findMethods(result, methods); if (candidates == null || candidates.length == 0) return null; return (JavaElement) candidates[0]; } }
private IMethod getMethodInWorkingCopy(IMethod method, String elementName, IType typeWc) { String[] paramTypeSignatures = method.getParameterTypes(); return typeWc.getMethod(elementName, paramTypeSignatures); }
/** {@inheritDoc} */ public Object execute(CommandLine commandLine) throws Exception { String project = commandLine.getValue(Options.PROJECT_OPTION); String file = commandLine.getValue(Options.FILE_OPTION); String propertiesOption = commandLine.getValue(Options.PROPERTIES_OPTION); String[] properties = {}; if (propertiesOption != null) { properties = StringUtils.split(propertiesOption, ','); } int offset = getOffset(commandLine); // validate supplied fields. ICompilationUnit src = JavaUtils.getCompilationUnit(project, file); IType type = TypeUtils.getType(src, offset); for (int ii = 0; ii < properties.length; ii++) { if (!type.getField(properties[ii]).exists()) { throw new RuntimeException( Services.getMessage("field.not.found", properties[ii], type.getElementName())); } } // check if constructor already exists. IMethod method = null; if (properties.length == 0) { method = type.getMethod(type.getElementName(), null); } else { String[] fieldSigs = new String[properties.length]; for (int ii = 0; ii < properties.length; ii++) { fieldSigs[ii] = type.getField(properties[ii]).getTypeSignature(); } method = type.getMethod(type.getElementName(), fieldSigs); } if (method.exists()) { throw new RuntimeException( Services.getMessage( "constructor.already.exists", type.getElementName() + " (" + buildParams(type, properties) + ")")); } // find the sibling to insert before. IJavaElement sibling = null; IMethod[] methods = type.getMethods(); for (int ii = 0; ii < methods.length; ii++) { if (methods[ii].isConstructor()) { sibling = ii < methods.length - 1 ? methods[ii + 1] : null; } } // insert before any other methods or inner classes if any. if (sibling == null) { if (methods.length > 0) { sibling = methods[0]; } else { IType[] types = type.getTypes(); sibling = types != null && types.length > 0 ? types[0] : null; } } HashMap<String, Object> values = new HashMap<String, Object>(); values.put("type", type.getElementName()); boolean hasProperties = properties != null && properties.length > 0; values.put("fields", hasProperties ? properties : null); values.put("params", hasProperties ? buildParams(type, properties) : StringUtils.EMPTY); PluginResources resources = (PluginResources) Services.getPluginResources(PluginResources.NAME); String constructor = TemplateUtils.evaluate(resources, TEMPLATE, values); Position position = TypeUtils.getPosition(type, type.createMethod(constructor, sibling, false, null)); JavaUtils.format( src, CodeFormatter.K_COMPILATION_UNIT, position.getOffset(), position.getLength()); return null; }
public static IMethod getMethod(IType t, String methodName, String[] params) { if (t == null || methodName == null || params == null) { return null; } return t.getMethod(methodName, params); }