Example usage for org.eclipse.jdt.core.util IClassFileReader getMethodInfos

List of usage examples for org.eclipse.jdt.core.util IClassFileReader getMethodInfos

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.util IClassFileReader getMethodInfos.

Prototype

IMethodInfo[] getMethodInfos();

Source Link

Document

Answer back the array of method infos of this .class file, an empty array if none.

Usage

From source file:com.inepex.classtemplater.plugin.logic.Annotation.java

License:Eclipse Public License

public Annotation(IAnnotation jdtAnnotation, ICompilationUnit compilationUnit) throws Exception {
    this.compilationUnit = compilationUnit;
    name = jdtAnnotation.getElementName();

    //default values aren't found in JDT so using AST to get them
    String[][] type = compilationUnit.findPrimaryType().resolveType(jdtAnnotation.getElementName());
    if (type != null) {
        IType annType = jdtAnnotation.getJavaProject().findType(type[0][0] + "." + type[0][1]);

        //hint to read annotation default value from a classfile
        //                  

        if (annType.getCompilationUnit() != null) {
            AnnotationASTVisitor annASTVisitor = new AnnotationASTVisitor();
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setKind(ASTParser.K_COMPILATION_UNIT);
            parser.setSource(annType.getCompilationUnit());
            parser.setResolveBindings(true);
            CompilationUnit aParser = (CompilationUnit) parser.createAST(null);
            aParser.accept(annASTVisitor);
            Map<String, Object> defaultValues = annASTVisitor.getDefaultValueObjects();
            for (Entry<String, Object> entry : defaultValues.entrySet()) {
                paramObjects.put(entry.getKey(), entry.getValue());
                params.put(entry.getKey(), String.valueOf(entry.getValue()));
            }//from   w w  w.  j  a v a 2s  . co  m
        } else {
            //read annotation default value from .class file
            IClassFileReader reader = ToolFactory.createDefaultClassFileReader(annType.getClassFile(),
                    IClassFileReader.ALL);
            if (reader != null) {
                for (IMethodInfo methodInfo : reader.getMethodInfos()) {
                    if (methodInfo.getAttributes().length > 0
                            && methodInfo.getAttributes()[0] instanceof AnnotationDefaultAttribute) {
                        String name = new String(methodInfo.getName());
                        Object value = parseDefaultObjectValueFromAnnotationDefaultAttribute(
                                (AnnotationDefaultAttribute) (methodInfo.getAttributes()[0]),
                                new String(methodInfo.getDescriptor()));
                        if (value != null) {
                            paramObjects.put(name, value);
                            params.put(name, String.valueOf(value));
                        }
                    }
                    //                  System.out.println(methodInfo.getName());

                }
            }
        }
    }

    for (IMemberValuePair pair : jdtAnnotation.getMemberValuePairs()) {
        try {
            params.put(pair.getMemberName(), String.valueOf(pair.getValue()));
            paramObjects.put(pair.getMemberName(), pair.getValue());
        } catch (ClassCastException e) {
            Log.log("Could not cast value of annotation-attribute: " + name + ", " + pair.getMemberName()
                    + ". \n" + "Only string values can be used for annotation-attribute");
        }
    }
}

From source file:com.siteview.mde.internal.ui.search.dependencies.PackageFinder.java

License:Open Source License

static void computeReferencedTypes(IClassFileReader cfr, Set packages) {

    char[][] interfaces = cfr.getInterfaceNames();
    if (interfaces != null) {
        for (int i = 0; i < interfaces.length; i++) {
            //note: have to convert names like Ljava/lang/Object; to java.lang.Object
            packages.add(getPackage(new String(interfaces[i]).replace('/', '.')));
        }//from  w  ww  .j av a 2  s.c  o  m
    }

    char[] scn = cfr.getSuperclassName();
    if (scn != null) {
        packages.add(getPackage(new String(scn).replace('/', '.')));
    }

    IFieldInfo[] fieldInfo = cfr.getFieldInfos();
    for (int i = 0; i < fieldInfo.length; i++) {

        String fieldName = new String(fieldInfo[i].getDescriptor());
        if (!isPrimitiveTypeSignature(fieldName)) {
            String fieldDescriptor = extractFullyQualifiedTopLevelType(fieldName);
            packages.add(getPackage(new String(fieldDescriptor)));
        }
    }

    IMethodInfo[] methodInfo = cfr.getMethodInfos();
    for (int i = 0; i < methodInfo.length; i++) {
        IExceptionAttribute exceptionAttribute = methodInfo[i].getExceptionAttribute();
        if (exceptionAttribute != null) {
            char[][] exceptionNames = exceptionAttribute.getExceptionNames();
            for (int j = 0; j < exceptionNames.length; j++) {
                packages.add(getPackage(new String(exceptionNames[j]).replace('/', '.')));
            }
        }

        String descriptor = new String(methodInfo[i].getDescriptor());
        //add parameter types
        String[] parameterTypes = Signature.getParameterTypes(descriptor);
        for (int j = 0; j < parameterTypes.length; j++) {
            //have to parse to convert [Ljava/lang/String; to java.lang.String
            if (!isPrimitiveTypeSignature(parameterTypes[j])) {
                packages.add(getPackage(new String(extractFullyQualifiedTopLevelType(parameterTypes[j]))));
            }
        }
        //add return type
        String returnType = Signature.getReturnType(descriptor);
        if (!isPrimitiveTypeSignature(returnType)) {
            returnType = extractFullyQualifiedTopLevelType(returnType);
            packages.add(getPackage(returnType));
        }
    }

    // Is there more to extract from the constant pool??
    IConstantPoolEntry entry;
    IConstantPool pool = cfr.getConstantPool();
    int length = pool.getConstantPoolCount();
    for (int i = 1; i < length; i++) {
        switch (pool.getEntryKind(i)) {
        case IConstantPoolConstant.CONSTANT_Class:
            // add reference to the class
            entry = pool.decodeEntry(i);
            //note: may have to convert names like Ljava/lang/Object; to java.lang.Object
            String className = new String(entry.getClassInfoName()).replace('/', '.');
            className = className.indexOf(';') >= 0 ? extractFullyQualifiedTopLevelType(className) : className;
            packages.add(getPackage(className));
            break;

        case IConstantPoolConstant.CONSTANT_NameAndType:
            // add reference to the name and type
            entry = pool.decodeEntry(i);
            int descIndex = entry.getNameAndTypeInfoDescriptorIndex();
            if (pool.getEntryKind(descIndex) == IConstantPoolConstant.CONSTANT_Utf8) {
                entry = pool.decodeEntry(descIndex);
                char[] type = entry.getUtf8Value();
                if (type[0] == '(') {
                    // Method signature.

                    //add parameter types
                    String descriptor = new String(type);
                    String[] parameterTypes = Signature.getParameterTypes(descriptor);
                    for (int j = 0; j < parameterTypes.length; j++) {
                        if (!isPrimitiveTypeSignature(parameterTypes[j])) {
                            packages.add(getPackage(extractFullyQualifiedTopLevelType(parameterTypes[j])));
                        }
                    }
                    //add return type
                    String returnType = Signature.getReturnType(descriptor);
                    if (!isPrimitiveTypeSignature(returnType)) {
                        returnType = extractFullyQualifiedTopLevelType(returnType);
                        packages.add(getPackage(returnType));
                    }

                } else {
                    // Field type.
                    String typeString = new String(type);
                    if (!isPrimitiveTypeSignature(typeString)) {
                        packages.add(getPackage(extractFullyQualifiedTopLevelType(typeString)));
                    }
                }
            }
            break;
        }
    }
    packages.remove(""); // removes default package if it exists //$NON-NLS-1$
}

From source file:de.bodden.tamiflex.resolution.MethodResolver.java

License:Open Source License

private static void disambiguateMethodByLineNumber(String containerClassName, String methodName,
        IProject containerProject, int lineNumber) {
    IJavaProject javaProject = JavaCore.create(containerProject);
    try {/*from  www  .  j  av a 2  s . c  o  m*/
        IType type = javaProject.findType(containerClassName, (IProgressMonitor) null);
        ICompilationUnit compilationUnit = type.getCompilationUnit();

        if (compilationUnit != null) {
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setSource(compilationUnit);
            parser.setResolveBindings(true);

            CompilationUnit cu = (CompilationUnit) parser.createAST(null);
            final int linePosition = cu.getPosition(lineNumber, 0);

            cu.accept(new ASTVisitor() {

                public boolean visit(MethodDeclaration method) {
                    if (method.getStartPosition() <= linePosition
                            && method.getStartPosition() + method.getLength() >= linePosition) {
                        //method is resolved
                        resolvedMethods.clear();
                        resolvedMethods.add((IMethod) method.resolveBinding().getJavaElement());
                    }
                    return false;
                }

            });
        } else {
            IClassFile classFile = type.getClassFile();
            if (classFile != null) {
                IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile,
                        IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
                for (IMethodInfo method : reader.getMethodInfos()) {
                    String currMethodName = new String(method.getName());
                    if (!currMethodName.equals(methodName))
                        continue;

                    ICodeAttribute codeAttribute = method.getCodeAttribute();
                    ILineNumberAttribute lineNumberAttribute = codeAttribute.getLineNumberAttribute();
                    if (lineNumberAttribute != null) {
                        int[][] lineNumberTable = lineNumberAttribute.getLineNumberTable();
                        if (lineNumberTable != null && lineNumberTable.length > 0) {
                            int startLine = Integer.MAX_VALUE;
                            int endLine = 0;
                            for (int[] entry : lineNumberTable) {
                                int line = entry[1];
                                startLine = Math.min(startLine, line);
                                endLine = Math.max(endLine, line);
                            }
                            if (startLine >= lineNumber && endLine <= lineNumber) {
                                char[][] parameterTypes = Signature.getParameterTypes(method.getDescriptor());
                                String[] parameterTypeNames = new String[parameterTypes.length];
                                int i = 0;
                                for (char[] cs : parameterTypes) {
                                    parameterTypeNames[i] = new String(cs);
                                    i++;
                                }
                                IMethod iMethod = type.getMethod(currMethodName, parameterTypeNames);

                                //method resolved
                                resolvedMethods.clear();
                                resolvedMethods.add(iMethod);
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:edu.uci.ics.sourcerer.tools.java.extractor.eclipse.NamingAdvisor.java

License:Open Source License

private void addClassFile(IClassFile classFile) {
    IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile,
            IClassFileReader.CONSTANT_POOL | IClassFileReader.METHOD_INFOS);
    IConstantPool constants = reader.getConstantPool();
    for (int i = 0, max = constants.getConstantPoolCount(); i < max; i++) {
        switch (constants.getEntryKind(i)) {
        case IConstantPoolConstant.CONSTANT_Class: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addClass(new String(constant.getClassInfoName()).replace('/', '.'));
            break;
        }/*from ww  w .  jav a 2 s.c  o m*/
        case IConstantPoolConstant.CONSTANT_Fieldref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addClassSig(constant.getFieldDescriptor());
            break;
        }
        case IConstantPoolConstant.CONSTANT_Methodref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addMethod(new String(constant.getClassName()), new String(constant.getMethodName()),
                    constant.getMethodDescriptor());
            break;
        }
        case IConstantPoolConstant.CONSTANT_InterfaceMethodref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addMethod(new String(constant.getClassName()), new String(constant.getMethodName()),
                    constant.getMethodDescriptor());
            break;
        }
        default:
        }
    }

    // Add the method parameter / return types
    for (IMethodInfo method : reader.getMethodInfos()) {
        for (char[] p : Signature.getParameterTypes(method.getDescriptor())) {
            addClassSig(p);
        }
        addClassSig(Signature.getReturnType(method.getDescriptor()));
    }
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

License:Open Source License

/**
 * Verify if the given <code>classFileReader</code> has code attributes.
 *
 * @param classFileReader/*from ww w .j a v  a  2 s.  c o m*/
 * @return
 */
static private boolean isEvisceratedClass(IClassFileReader classFileReader) {
    // ignore interface classes
    if (!classFileReader.isClass()) {
        return false;
    }
    IMethodInfo[] methodInfos = classFileReader.getMethodInfos();
    if (methodInfos == null) {
        return false;
    }
    for (int i = 0; i < methodInfos.length; i++) {
        // Ignore <init>, <clinit> and abstract methods
        if ("<init>".equalsIgnoreCase(String.valueOf(methodInfos[i].getName())) || methodInfos[i].isClinit()
                || (methodInfos[i].getAccessFlags() & IModifierConstants.ACC_ABSTRACT) != 0) {
            continue;
        }
        if (methodInfos[i].getCodeAttribute() == null) {
            return true;
        }
    }
    return false;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.AJSerialVersionHashOperation.java

License:Open Source License

private static boolean hasStaticClassInitializer(IClassFileReader cfReader) {
    IMethodInfo[] methodInfos = cfReader.getMethodInfos();
    for (int i = 0; i < methodInfos.length; i++) {
        if (methodInfos[i].isClinit()) {
            return true;
        }/*from  w  w  w .ja v  a  2  s  . c  o  m*/
    }
    return false;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.AJSerialVersionHashOperation.java

License:Open Source License

private static IMethodInfo[] getSortedMethods(IClassFileReader cfReader) {
    IMethodInfo[] allMethods = cfReader.getMethodInfos();
    Arrays.sort(allMethods, new Comparator() {
        public int compare(Object o1, Object o2) {
            IMethodInfo mi1 = (IMethodInfo) o1;
            IMethodInfo mi2 = (IMethodInfo) o2;
            if (mi1.isConstructor() != mi2.isConstructor()) {
                return mi1.isConstructor() ? -1 : 1;
            } else if (mi1.isConstructor()) {
                return 0;
            }//from w w  w  . j  av a2  s .c  om
            int res = CharOperation.compareTo(mi1.getName(), mi2.getName());
            if (res != 0) {
                return res;
            }
            return CharOperation.compareTo(mi1.getDescriptor(), mi2.getDescriptor());
        }
    });
    return allMethods;
}

From source file:org.eclipse.pde.internal.ui.search.dependencies.PackageFinder.java

License:Open Source License

static void computeReferencedTypes(IClassFileReader cfr, Set<String> packages) {

    char[][] interfaces = cfr.getInterfaceNames();
    if (interfaces != null) {
        for (int i = 0; i < interfaces.length; i++) {
            //note: have to convert names like Ljava/lang/Object; to java.lang.Object
            packages.add(getPackage(new String(interfaces[i]).replace('/', '.')));
        }//from   w  w  w  .jav a 2  s .co m
    }

    char[] scn = cfr.getSuperclassName();
    if (scn != null) {
        packages.add(getPackage(new String(scn).replace('/', '.')));
    }

    IFieldInfo[] fieldInfo = cfr.getFieldInfos();
    for (int i = 0; i < fieldInfo.length; i++) {

        String fieldName = new String(fieldInfo[i].getDescriptor());
        if (!isPrimitiveTypeSignature(fieldName)) {
            String fieldDescriptor = extractFullyQualifiedTopLevelType(fieldName);
            packages.add(getPackage(new String(fieldDescriptor)));
        }
    }

    IMethodInfo[] methodInfo = cfr.getMethodInfos();
    for (int i = 0; i < methodInfo.length; i++) {
        IExceptionAttribute exceptionAttribute = methodInfo[i].getExceptionAttribute();
        if (exceptionAttribute != null) {
            char[][] exceptionNames = exceptionAttribute.getExceptionNames();
            for (int j = 0; j < exceptionNames.length; j++) {
                packages.add(getPackage(new String(exceptionNames[j]).replace('/', '.')));
            }
        }

        String descriptor = new String(methodInfo[i].getDescriptor());
        //add parameter types
        String[] parameterTypes = Signature.getParameterTypes(descriptor);
        for (int j = 0; j < parameterTypes.length; j++) {
            //have to parse to convert [Ljava/lang/String; to java.lang.String
            if (!isPrimitiveTypeSignature(parameterTypes[j])) {
                packages.add(getPackage(new String(extractFullyQualifiedTopLevelType(parameterTypes[j]))));
            }
        }
        //add return type
        String returnType = Signature.getReturnType(descriptor);
        if (!isPrimitiveTypeSignature(returnType)) {
            returnType = extractFullyQualifiedTopLevelType(returnType);
            packages.add(getPackage(returnType));
        }
    }

    // Is there more to extract from the constant pool??
    IConstantPoolEntry entry;
    IConstantPool pool = cfr.getConstantPool();
    int length = pool.getConstantPoolCount();
    for (int i = 1; i < length; i++) {
        switch (pool.getEntryKind(i)) {
        case IConstantPoolConstant.CONSTANT_Class:
            // add reference to the class
            entry = pool.decodeEntry(i);
            //note: may have to convert names like Ljava/lang/Object; to java.lang.Object
            String className = new String(entry.getClassInfoName()).replace('/', '.');
            className = className.indexOf(';') >= 0 ? extractFullyQualifiedTopLevelType(className) : className;
            packages.add(getPackage(className));
            break;

        case IConstantPoolConstant.CONSTANT_NameAndType:
            // add reference to the name and type
            entry = pool.decodeEntry(i);
            int descIndex = entry.getNameAndTypeInfoDescriptorIndex();
            if (pool.getEntryKind(descIndex) == IConstantPoolConstant.CONSTANT_Utf8) {
                entry = pool.decodeEntry(descIndex);
                char[] type = entry.getUtf8Value();
                if (type[0] == '(') {
                    // Method signature.

                    //add parameter types
                    String descriptor = new String(type);
                    String[] parameterTypes = Signature.getParameterTypes(descriptor);
                    for (int j = 0; j < parameterTypes.length; j++) {
                        if (!isPrimitiveTypeSignature(parameterTypes[j])) {
                            packages.add(getPackage(extractFullyQualifiedTopLevelType(parameterTypes[j])));
                        }
                    }
                    //add return type
                    String returnType = Signature.getReturnType(descriptor);
                    if (!isPrimitiveTypeSignature(returnType)) {
                        returnType = extractFullyQualifiedTopLevelType(returnType);
                        packages.add(getPackage(returnType));
                    }

                } else {
                    // Field type.
                    String typeString = new String(type);
                    if (!isPrimitiveTypeSignature(typeString)) {
                        packages.add(getPackage(extractFullyQualifiedTopLevelType(typeString)));
                    }
                }
            }
            break;
        }
    }
    packages.remove(""); // removes default package if it exists //$NON-NLS-1$
}

From source file:org.eclipse.pde.tools.internal.versioning.JavaClassVersionCompare.java

License:Open Source License

/**
 * compares two java classes denoted by <code>classFileReader1</code> and <code>classFileReader2</code>,
 * and check if there is any change from <code>classFileReader2</code> to <code>classFileReader1</code>.
 * // w  ww.j  ava  2s  .c o  m
 * @param classFileReader1
 * @param classFileReader2
 * @param monitor IProgressMonitor instance
 * @return compare result IStatus instance
 */
private IStatus compareJavaClasses(IClassFileReader classFileReader1, IClassFileReader classFileReader2,
        IProgressMonitor monitor) {
    try {
        monitor.beginTask("", 100); //$NON-NLS-1$
        // compare class names
        String name1 = charsToString(classFileReader1.getClassName());
        String name2 = charsToString(classFileReader2.getClassName());
        if (!name1.equals(name2)) {
            finalResult.merge(resultStatusHandler(IStatus.WARNING, IVersionCompare.PROCESS_ERROR_STATUS,
                    NLS.bind(Messages.JavaClassVersionCompare_differentClassNameMsg, name1, name2), null));
            return finalResult;
        }
        // worked 5%
        monitor.worked(5);
        // compare super classes
        checkSuperClasses(name1, classFileReader1.getSuperclassName(), classFileReader2.getSuperclassName());
        // worked 5%
        monitor.worked(5);
        // compare interfaces
        checkInterfaces(name1, generateList(classFileReader1.getInterfaceNames()),
                generateList(classFileReader2.getInterfaceNames()));
        // worked 5%
        monitor.worked(5);
        // compare modifier of classes
        checkClassModifiers(name1, classFileReader1.getAccessFlags(), classFileReader2.getAccessFlags());
        // worked 5%
        monitor.worked(5);
        // compare fields
        checkElements(name1, generateTable(classFileReader1.getFieldInfos()),
                generateTable(classFileReader2.getFieldInfos()));
        // worked 40%
        monitor.worked(40);
        // compare methods (40%)
        checkElements(name1, generateTable(classFileReader1.getMethodInfos()),
                generateTable(classFileReader2.getMethodInfos()));
        return finalResult;
    } finally {
        monitor.done();
    }
}