List of usage examples for org.eclipse.jdt.core IMethod getSignature
String getSignature() throws JavaModelException;
From source file:at.bestsolution.fxide.jdt.editor.internal.MethodUtil.java
License:Open Source License
/** * Tests if a method equals to the given signature. Parameter types are only * compared by the simple name, no resolving for the fully qualified type * name is done. Constructors are only compared by parameters, not the name. * * @param name Name of the method/*from w w w.j a v a2 s.c om*/ * @param paramTypes The type signatures of the parameters e.g. * <code>{"QString;","I"}</code> * @param isConstructor Specifies if the method is a constructor * @param method the method to be compared with this info's method * @param typeVariables a map from type variables to types * @param type the given type that declares the method * @return Returns <code>true</code> if the method has the given name and * parameter types and constructor state. * @throws JavaModelException if the method does not exist or if an exception occurs while accessing its corresponding resource */ private boolean isSameMethodSignature(String name, String[] paramTypes, boolean isConstructor, IMethod method, Map<String, char[]> typeVariables, IType type) throws JavaModelException { if (isConstructor || name.equals(method.getElementName())) { if (isConstructor == method.isConstructor()) { String[] otherParams = method.getParameterTypes(); // types may be type variables boolean isBinaryConstructorForNonStaticMemberClass = method.isBinary() && type.isMember() && !Flags.isStatic(type.getFlags()); int syntheticParameterCorrection = isBinaryConstructorForNonStaticMemberClass && paramTypes.length == otherParams.length - 1 ? 1 : 0; if (paramTypes.length == otherParams.length - syntheticParameterCorrection) { fFallbackMatch = method; String signature = method.getSignature(); String[] otherParamsFromSignature = Signature.getParameterTypes(signature); // types are resolved / upper-bounded // no need to check method type variables since these are // not yet bound when proposing a method for (int i = 0; i < paramTypes.length; i++) { String ourParamName = computeSimpleTypeName(paramTypes[i], typeVariables); String otherParamName1 = computeSimpleTypeName( otherParams[i + syntheticParameterCorrection], typeVariables); String otherParamName2 = computeSimpleTypeName( otherParamsFromSignature[i + syntheticParameterCorrection], typeVariables); if (!ourParamName.equals(otherParamName1) && !ourParamName.equals(otherParamName2)) { return false; } } return true; } } } return false; }
From source file:com.dforensic.plugin.manal.parser.SuspectSearch.java
License:Open Source License
private void extractMethodDetails(IType type) throws JavaModelException { IMethod[] methods = type.getMethods(); for (IMethod method : methods) { ApiDescriptor apiDesc = new ApiDescriptor(); apiDesc.setMethodName(method.getElementName()); apiDesc.setReturnType(method.getReturnType()); apiDesc.setSignature(method.getSignature()); mMethodDetails.add(apiDesc);//from ww w .ja va 2 s . c om } }
From source file:com.drgarbage.controlflowgraphfactory.actions.GenerateGraphAction.java
License:Apache License
/** * Process all parents from the selected node by calling getParent() method. * Tree | Interfaces * ---------------------------------+----------- * Project | IJavaElement, IJavaProject * + Package | IJavaElement, IPackageFragment * + Source: *.java or *.class | IJavaElement * + Class | IJavaElement, IType * + Method | IJavaElement, IMethod * /*from w ww .ja v a2 s.c o m*/ * Classpath for the selected class files can be resolved from the * project tree node by calling getPath() method. * Classpath for the source files should be resolved via Java runtime, * because it can be different with the source path. * */ private void createControlFlowGraph(TreeSelection treeSel) { String mMethodName = null; String mMethodSignature = null; String mClassName = null; String mPackage = null; List<String> mPath = new ArrayList<String>(); /* java model elements */ IMethod iMethod = null; IJavaProject jp = null; try { /* Method Name */ iMethod = (IMethod) treeSel.getFirstElement(); if (!hasCode(iMethod)) { Messages.info(MessageFormat.format(CoreMessages.CannotGenerateGraph_MethodIsAnAbstractMethod, new Object[] { iMethod.getElementName() })); return; } if (iMethod.isConstructor()) { mMethodName = "<init>"; } else { mMethodName = iMethod.getElementName(); } /** * Method Signature: * NOTE: if class file is selected then the method signature is resolved. */ if (iMethod.isBinary()) { mMethodSignature = iMethod.getSignature(); } else { try { /* resolve parameter signature */ StringBuffer buf = new StringBuffer("("); String[] parameterTypes = iMethod.getParameterTypes(); String res = null; for (int i = 0; i < parameterTypes.length; i++) { res = ActionUtils.getResolvedTypeName(parameterTypes[i], iMethod.getDeclaringType()); buf.append(res); } buf.append(")"); res = ActionUtils.getResolvedTypeName(iMethod.getReturnType(), iMethod.getDeclaringType()); buf.append(res); mMethodSignature = buf.toString(); } catch (IllegalArgumentException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } } IType type = iMethod.getDeclaringType(); mClassName = type.getFullyQualifiedName(); mPackage = type.getPackageFragment().getElementName(); mClassName = mClassName.replace(mPackage + ".", ""); if (iMethod.isBinary()) { /* Classpath for selected class files */ mPath.add(type.getPackageFragment().getPath().toString()); } /* Classpath for selected source code files */ jp = iMethod.getJavaProject(); try { String[] str = JavaRuntime.computeDefaultRuntimeClassPath(jp); for (int i = 0; i < str.length; i++) { mPath.add(str[i]); } } catch (CoreException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } } catch (ClassCastException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } catch (JavaModelException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } /* convert classpath to String array */ String[] classPath = new String[mPath.size()]; for (int i = 0; i < mPath.size(); i++) { classPath[i] = mPath.get(i); } /* create control flow graph diagram */ final ControlFlowGraphDiagram controlFlowGraphDiagram = createDiagram(classPath, mPackage, mClassName, mMethodName, mMethodSignature); if (controlFlowGraphDiagram == null) { Messages.warning(ControlFlowFactoryMessages.DiagramIsNullMessage); return; } /* create empty shell */ Shell shell = page.getActivePart().getSite().getShell(); /* Show a SaveAs dialog */ ExportGraphSaveAsDialog dialog = new ExportGraphSaveAsDialog(shell); try { IPath path = jp.getCorrespondingResource().getFullPath(); if (iMethod.isConstructor()) { /* use class name for constructor */ path = path.append(IPath.SEPARATOR + mClassName + "." + mClassName + "." + GraphConstants.graphTypeSuffixes[getGraphType()]); } else { path = path.append(IPath.SEPARATOR + mClassName + "." + mMethodName + "." + GraphConstants.graphTypeSuffixes[getGraphType()]); } path = path.addFileExtension(FileExtensions.GRAPH); /* get file and set in the dialog */ IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path); dialog.setOriginalFile(file); } catch (JavaModelException e) { ControlFlowFactoryPlugin.getDefault().getLog() .log(new Status(IStatus.ERROR, ControlFlowFactoryPlugin.PLUGIN_ID, e.getMessage(), e)); Messages.error(e.getMessage() + CoreMessages.ExceptionAdditionalMessage); return; } /* open SaveAS dialog */ dialog.open(); IPath path = dialog.getResult(); if (path == null) {/* action canceled */ return; } graphSpecification = dialog.getGraphSpecification(); /* convert if necessary and start an editor */ switch (graphSpecification.getExportFormat()) { case GraphConstants.EXPORT_FORMAT_DRGARBAGE_GRAPH: ActionUtils.saveDiagramInFileAndOpenEditor(path, shell, page, controlFlowGraphDiagram, graphSpecification.isOpenInEditor()); break; default: AbstractExport2 exporter = null; switch (graphSpecification.getExportFormat()) { case GraphConstants.EXPORT_FORMAT_DOT: exporter = new GraphDOTExport(); break; case GraphConstants.EXPORT_FORMAT_GRAPHXML: exporter = new GraphXMLExport(); break; case GraphConstants.EXPORT_FORMAT_GRAPHML: exporter = new GraphMlExport(); break; default: throw new IllegalStateException( "Unexpected export format '" + graphSpecification.getExportFormat() + "'."); } exporter.setGraphSpecification(graphSpecification); StringWriter sb = new StringWriter(); try { exporter.write(controlFlowGraphDiagram, sb); } catch (ExportException e) { /* This will never happen as * StringBuilder.append(*) does not throw IOException*/ throw new RuntimeException(e); } ActionUtils.saveContentInFileAndOpenEditor(path, shell, page, sb.toString(), graphSpecification.isOpenInEditor()); break; } dialog = null; }
From source file:com.drgarbage.utils.ClassFileDocumentsUtils.java
License:Apache License
/** * Returns the method signature string./* w w w. java 2 s . c om*/ * @param iMethod method object * @return method signature string * * @see IMethod */ public static String resolveMethodSignature(IMethod iMethod) { String mMethodSignature = null; try { /* * Method Signature: * NOTE: if class file is selected then the method signature is resolved. */ if (iMethod.isBinary()) { mMethodSignature = iMethod.getSignature(); } else { /* resolve parameter signature */ StringBuffer buf = new StringBuffer("("); String[] parameterTypes = iMethod.getParameterTypes(); String res = null; for (int i = 0; i < parameterTypes.length; i++) { res = com.drgarbage.core.ActionUtils.getResolvedTypeName(parameterTypes[i], iMethod.getDeclaringType()); buf.append(res); } buf.append(")"); res = com.drgarbage.core.ActionUtils.getResolvedTypeName(iMethod.getReturnType(), iMethod.getDeclaringType()); buf.append(res); mMethodSignature = buf.toString(); } } catch (IllegalArgumentException e) { handleException(e); return null; } catch (JavaModelException e) { handleException(e); return null; } return mMethodSignature; }
From source file:com.google.gdt.eclipse.appengine.rpc.util.CompilationUnitCreator.java
License:Open Source License
/** * Constructs the proxy body//from w w w . j av a 2 s. c om */ private void constructProxyBody(IType type, ImportsManager imports, IProgressMonitor monitor) throws JavaModelException { imports.addImport("com.google.web.bindery.requestfactory.shared.ProxyForName"); //$NON-NLS-N$ StringBuffer buf = new StringBuffer(); IImportDeclaration[] importDeclarations = current.getCompilationUnit().getImports(); // create list of entity names List<String> entityNameList = new ArrayList<String>(); for (IType entity : entityList) { entityNameList.add(entity.getElementName()); } // get list of all property methods List<IMethod> methods = new ArrayList<IMethod>(); for (IMethod method : current.getMethods()) { if (RequestFactoryUtils.isPropertyAccessor(method) && !method.getElementName().equals("setId")) { //$NON-NLS-N$ methods.add(method); } } boolean hasProxy; Set<String> typeNames; for (IMethod method : methods) { hasProxy = false; String methodName = method.getElementName(); String signature = Signature.toString(method.getSignature(), methodName, method.getParameterNames(), false, true); typeNames = new HashSet<String>(); typeNames.addAll(JavaUtils.getParamsAndReturnTypeNames(method)); hasProxy = addImport(typeNames, entityNameList, importDeclarations, imports); // check if to replace Task with TaskProxy if (hasProxy) { for (String entityName : entityNameList) { if (signature.contains(entityName)) { if (methodName.contains("get") || methodName.contains("is") || methodName.contains("has")) { //$NON-NLS-N$ signature = signature.replaceFirst(entityName, entityName + "Proxy"); //$NON-NLS-N$ } else if (methodName.contains("set")) { //$NON-NLS-N$ int index = signature.lastIndexOf(entityName); signature = signature.substring(0, index) + entityName + "Proxy" //$NON-NLS-N$ + signature.substring(index + entityName.length()); } } } } buf.append(signature); buf.append(";"); //$NON-NLS-N$ buf.append(lineDelimiter); } if (!methods.isEmpty()) { type.createMethod(buf.toString(), null, false, null); } if (monitor != null) { monitor.done(); } }
From source file:com.google.gdt.eclipse.appengine.rpc.util.RequestFactoryCodegenUtils.java
License:Open Source License
/** * Construct the signature for method added to service class, to be added to * the requestcontext/* ww w . j a va 2s . com*/ */ public static String constructMethodSignature(IMethod serviceMethod, List<IType> projectEntities) { StringBuffer buf = new StringBuffer(); try { buf.append("Request<"); String methodName = serviceMethod.getElementName(); String signature = Signature.toString(serviceMethod.getSignature(), methodName, serviceMethod.getParameterNames(), false, true); signature = signature.replace(methodName, ""); for (IType entity : projectEntities) { if (signature.contains(entity.getElementName())) { signature = signature.replace(entity.getElementName(), entity.getElementName() + "Proxy"); } } signature = signature.replace("void", "Void"); int index = signature.indexOf(" "); signature = signature.substring(0, index) + "> " + methodName + signature.substring(index) + ";"; buf.append(signature); } catch (JavaModelException e) { AppEngineRPCPlugin.log(e); } return buf.toString(); }
From source file:com.google.gdt.eclipse.appengine.rpc.wizards.helpers.RpcServiceLayerCreator.java
License:Open Source License
private void constructProxyBody(IType type, ImportsManager imports, IProgressMonitor monitor) throws JavaModelException { imports.addImport("com.google.web.bindery.requestfactory.shared.ProxyForName"); //$NON-NLS-N$ StringBuffer buf = new StringBuffer(); IImportDeclaration[] importDeclarations = current.getCompilationUnit().getImports(); // create list of entity names List<String> entityNameList = new ArrayList<String>(); for (IType entity : entityList) { entityNameList.add(entity.getElementName()); }/* ww w .j ava 2s. c o m*/ // get list of all property methods List<IMethod> methods = new ArrayList<IMethod>(); for (IMethod method : current.getMethods()) { if (RequestFactoryUtils.isPropertyAccessor(method) && !method.getElementName().equals("setId")) { methods.add(method); } } boolean hasProxy; List<String> typeNames; for (IMethod method : methods) { hasProxy = false; String methodName = method.getElementName(); String signature = Signature.toString(method.getSignature(), methodName, method.getParameterNames(), false, true); typeNames = new ArrayList<String>(); String returnType[] = getElementSignatures(method.getReturnType()); for (String string : returnType) { typeNames.add(string); } String[] params = method.getParameterTypes(); // we are looking at only getters and setters, so there is only one param? if (params.length > 0) { String[] param = getElementSignatures(params[0]); for (String string : param) { typeNames.add(string); } } hasProxy = addImport(typeNames, entityNameList, importDeclarations, imports); // check if to replace Task with TaskProxy if (hasProxy) { for (String entityName : entityNameList) { if (signature.contains(entityName)) { if (methodName.contains("get") || methodName.contains("is") || methodName.contains("has")) { //$NON-NLS-N$ signature = signature.replaceFirst(entityName, entityName + "Proxy"); //$NON-NLS-N$ } else if (methodName.contains("set")) { //$NON-NLS-N$ int index = signature.lastIndexOf(entityName); signature = signature.substring(0, index) + entityName + "Proxy" //$NON-NLS-N$ + signature.substring(index + entityName.length()); } } } } buf.append(signature); buf.append(";"); //$NON-NLS-N$ buf.append(lineDelimiter); } if (!methods.isEmpty()) { type.createMethod(buf.toString(), null, false, null); } if (monitor != null) { monitor.done(); } }
From source file:com.google.gdt.eclipse.core.java.JavaModelSearch.java
License:Open Source License
private static boolean methodSignaturesEqual(IType type2, String methodName, String[] paramTypes, boolean isConstructor, IMethod method2) { try {// w w w . j a va 2 s . c o m // Method names must match, unless we're comparing constructors if (!isConstructor && !method2.getElementName().equals(methodName)) { return false; } // Only compare ctors to ctors and methods to methods if (isConstructor != method2.isConstructor()) { return false; } // Parameter count must match String signature2 = method2.getSignature(); String[] paramTypes2 = Signature.getParameterTypes(signature2); if (paramTypes.length != paramTypes2.length) { return false; } // Compare each parameter type for (int i = 0; i < paramTypes.length; i++) { String paramType = paramTypes[i]; String paramType2 = paramTypes2[i]; // Compare array nesting depth ([] = 1, [][] = 2, etc.) if (Signature.getArrayCount(paramType) != Signature.getArrayCount(paramType2)) { return false; } // Remove any array nesting and generic type parameters paramType = getBaseType(paramType); paramType2 = getBaseType(paramType2); // Extract the full type names from the signatures String paramTypeName = getQualifiedTypeName(paramType); String paramTypeName2 = getQualifiedTypeName(paramType2); if (isTypeParameter(method2, paramTypeName2)) { // Skip parameters whose type is a generic type parameter of the // method we're comparing against, or the method's containing class continue; /* * TODO: we're currently not checking the bounds of generic type * parameters, so sometimes we may return true here even when the * caller's method signature doesn't match the method we're comparing * against. We could try to add that logic here, or better still, we * could integrate TypeOracle and take advantage of its type searching * capabilities. */ } // If we run into an unresolved parameter type in the method we're // searching, we'll need to resolve that before doing the comparison if (paramType2.charAt(0) == Signature.C_UNRESOLVED) { paramTypeName2 = resolveTypeName(type2, paramTypeName2); } // Finally, compare the type names if (!paramTypeName.equals(paramTypeName2)) { return false; } } // We passed all the checks, so the signatures are equal return true; } catch (JavaModelException e) { CorePluginLog.logError(e, "Error comparing method signatures of {0} and {1}", methodName, method2.getElementName()); return false; } }
From source file:com.google.gwt.eclipse.core.uibinder.contentassist.computers.SetterAttributeProposalComputer.java
License:Open Source License
private String getDescription(IType type, IMethod method) { try {/* ww w . j av a 2 s . c o m*/ return MessageFormat.format(DESCRIPTION_FORMAT, type.getElementName(), Signature.toString( method.getSignature(), method.getElementName(), method.getParameterNames(), false, false)); } catch (JavaModelException e) { // if the above throws, we fall-back on a safer/simpler version return MessageFormat.format(DESCRIPTION_FORMAT, type.getElementName(), method.getElementName()); } }
From source file:com.ibm.research.tours.content.url.JavaURL.java
License:Open Source License
public String toPortableString() { String base = URLParser.ECLIPSE_PREAMBLE + fElement.getResource().getFullPath().toPortableString(); if (fElement.getElementType() == IJavaElement.TYPE) { IType type = (IType) fElement;//from ww w . j a v a 2s . co m String typeParam = TYPE_PARAM + URLParser.PARAMETER_EQUALS + TYPE_TYPE; String nameParam = SIGNATURE_PARAM + URLParser.PARAMETER_EQUALS + type.getTypeQualifiedName('.'); return base + URLParser.PARAMETER_START + typeParam + URLParser.PARAMETER_DELIM + nameParam; } if (fElement.getElementType() == IJavaElement.FIELD) { IField field = (IField) fElement; String typeParam = TYPE_PARAM + URLParser.PARAMETER_EQUALS + FIELD_TYPE; String nameParam = SIGNATURE_PARAM + URLParser.PARAMETER_EQUALS + field.getDeclaringType().getTypeQualifiedName('.') + "." + field.getElementName(); return base + URLParser.PARAMETER_START + typeParam + URLParser.PARAMETER_DELIM + nameParam; } if (fElement.getElementType() == IJavaElement.METHOD) { IMethod method = (IMethod) fElement; String signature = null; try { signature = Signature.toPortableString(method.getSignature(), method.getElementName(), false, false); } catch (JavaModelException e) { e.printStackTrace(); } String typeParam = TYPE_PARAM + URLParser.PARAMETER_EQUALS + METHOD_TYPE; String nameParam = SIGNATURE_PARAM + URLParser.PARAMETER_EQUALS + method.getDeclaringType().getTypeQualifiedName('.') + "." + signature; return base + URLParser.PARAMETER_START + typeParam + URLParser.PARAMETER_DELIM + nameParam; } return ""; }