Java Code Examples for org.apache.bcel.classfile.Method#getSignature()

The following examples show how to use org.apache.bcel.classfile.Method#getSignature() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UncallableMethodOfAnonymousClass.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
boolean definedInThisClassOrSuper(JavaClass clazz, String method) throws ClassNotFoundException {
    if (clazz == null) {
        return false;
    }
    // System.out.println("Checking to see if " + method + " is defined in "
    // + clazz.getClassName());
    for (Method m : clazz.getMethods()) {
        String key = m.getName() + ":" + m.getSignature();
        if (!m.isStatic() && method.equals(key)) {
            return true;
        }
    }

    return definedInSuperClassOrInterface(clazz, method);

}
 
Example 2
Source File: SelfCalls.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Is the given instruction a self-call?
 */
private Method isSelfCall(InvokeInstruction inv) {
    ConstantPoolGen cpg = classContext.getConstantPoolGen();
    JavaClass jclass = classContext.getJavaClass();

    String calledClassName = inv.getClassName(cpg);

    // FIXME: is it possible we would see a superclass name here?
    // Not a big deal for now, as we are mostly just interested in calls
    // to private methods, for which we will definitely see the right
    // called class name.
    if (!calledClassName.equals(jclass.getClassName())) {
        return null;
    }

    String calledMethodName = inv.getMethodName(cpg);
    String calledMethodSignature = inv.getSignature(cpg);
    boolean isStaticCall = (inv instanceof INVOKESTATIC);

    // Scan methods for one that matches.
    Method[] methods = jclass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        String signature = method.getSignature();
        boolean isStatic = method.isStatic();

        if (methodName.equals(calledMethodName) && signature.equals(calledMethodSignature) && isStatic == isStaticCall) {
            // This method looks like a match.
            return wantCallsFor(method) ? method : null;
        }
    }

    // Hmm...no matching method found.
    // This is almost certainly because the named method
    // was inherited from a superclass.
    LOG.debug("No method found for {}.{} : {}", calledClassName, calledMethodName, calledMethodSignature);
    return null;
}
 
Example 3
Source File: LocalVariableAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull LocalVariableAnnotation findUniqueBestMatchingParameter(ClassContext classContext, Method method, String name,
        String signature) {
    LocalVariableAnnotation match = null;
    int localsThatAreParameters = PreorderVisitor.getNumberArguments(method.getSignature());
    int startIndex = 0;
    if (!method.isStatic()) {
        startIndex = 1;
    }
    SignatureParser parser = new SignatureParser(method.getSignature());
    Iterator<String> signatureIterator = parser.parameterSignatureIterator();
    int lowestCost = Integer.MAX_VALUE;
    for (int i = startIndex; i < localsThatAreParameters + startIndex; i++) {
        String sig = signatureIterator.next();
        if (signature.equals(sig)) {
            LocalVariableAnnotation potentialMatch = LocalVariableAnnotation.getLocalVariableAnnotation(method, i, 0, 0);
            if (!potentialMatch.isNamed()) {
                continue;
            }
            int distance = EditDistance.editDistance(name, potentialMatch.getName());
            if (distance < lowestCost) {
                match = potentialMatch;
                match.setDescription(DID_YOU_MEAN_ROLE);
                lowestCost = distance;
            } else if (distance == lowestCost) {
                // not unique best match
                match = null;
            }
            // signatures match
        }
    }
    if (lowestCost < 5) {
        return match;
    }
    return null;
}
 
Example 4
Source File: UselessSubclassMethod.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitMethod(Method obj) {
    if ((interfaceMethods != null) && ((obj.getAccessFlags() & Const.ACC_ABSTRACT) != 0)) {
        String curDetail = obj.getName() + obj.getSignature();
        for (String infMethodDetail : interfaceMethods) {
            if (curDetail.equals(infMethodDetail)) {
                bugReporter.reportBug(new BugInstance(this, "USM_USELESS_ABSTRACT_METHOD", LOW_PRIORITY).addClassAndMethod(
                        getClassContext().getJavaClass(), obj));
            }
        }
    }
    super.visitMethod(obj);
}
 
Example 5
Source File: UncallableMethodOfAnonymousClass.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean skip(Method obj) {
    if (BCELUtil.isSynthetic(obj)) {
        return true;
    }
    if (obj.isPrivate()) {
        return true;
    }
    if (obj.isAbstract()) {
        return true;
    }

    String methodName = obj.getName();
    String sig = obj.getSignature();
    if (Const.CONSTRUCTOR_NAME.equals(methodName)) {
        return true;
    }
    if (Const.STATIC_INITIALIZER_NAME.equals(methodName)) {
        return true;
    }
    if ("()Ljava/lang/Object;".equals(sig) && ("readResolve".equals(methodName) || "writeReplace".equals(methodName))) {
        return true;
    }
    if (methodName.startsWith("access$")) {
        return true;
    }
    if (methodName.length() < 2 || methodName.indexOf('$') >= 0) {
        return true;
    }
    XMethod m = getXMethod();
    for (ClassDescriptor c : m.getAnnotationDescriptors()) {
        if (c.getClassName().indexOf("inject") >= 0) {
            return true;
        }
    }
    return false;
}
 
Example 6
Source File: OpcodeStackScanner.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static OpcodeStack getStackAt(JavaClass theClass, Method method, int pc) {
    Scanner scanner = new Scanner(theClass, method, pc);
    try {
        scanner.execute();
    } catch (EarlyExitException e) {
        return e.stack;
    }
    throw new UnreachableCodeException(theClass.getClassName(), method.getName(), method.getSignature(), pc);
}
 
Example 7
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the linkage errors for unimplemented methods in {@code classFile}. Such unimplemented
 * methods manifest as {@link AbstractMethodError} in runtime.
 */
private ImmutableList<SymbolProblem> findInterfaceProblems(
    ClassFile classFile, InterfaceSymbol interfaceSymbol) {
  String interfaceName = interfaceSymbol.getClassBinaryName();
  if (classDumper.isSystemClass(interfaceName)) {
    return ImmutableList.of();
  }

  ImmutableList.Builder<SymbolProblem> builder = ImmutableList.builder();
  try {
    JavaClass implementingClass = classDumper.loadJavaClass(classFile.getBinaryName());
    if (implementingClass.isAbstract()) {
      // Abstract class does not need to implement methods in an interface.
      return ImmutableList.of();
    }
    JavaClass interfaceDefinition = classDumper.loadJavaClass(interfaceName);
    for (Method interfaceMethod : interfaceDefinition.getMethods()) {
      if (interfaceMethod.getCode() != null) {
        // This interface method has default implementation. Subclass does not have to implement
        // it.
        continue;
      }
      String interfaceMethodName = interfaceMethod.getName();
      String interfaceMethodDescriptor = interfaceMethod.getSignature();
      boolean methodFound = false;

      Iterable<JavaClass> typesToCheck = Iterables.concat(getClassHierarchy(implementingClass));
      for (JavaClass javaClass : typesToCheck) {
        for (Method method : javaClass.getMethods()) {
          if (method.getName().equals(interfaceMethodName)
              && method.getSignature().equals(interfaceMethodDescriptor)) {
            methodFound = true;
            break;
          }
        }
      }
      if (!methodFound) {
        MethodSymbol missingMethodOnClass =
            new MethodSymbol(
                classFile.getBinaryName(), interfaceMethodName, interfaceMethodDescriptor, false);
        builder.add(
            new SymbolProblem(missingMethodOnClass, ErrorType.ABSTRACT_METHOD, classFile));
      }
    }
  } catch (ClassNotFoundException ex) {
    // Missing classes are reported by findSymbolProblem method.
  }
  return builder.build();
}
 
Example 8
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
private ImmutableList<SymbolProblem> findAbstractParentProblems(
    ClassFile classFile, SuperClassSymbol superClassSymbol) {
  ImmutableList.Builder<SymbolProblem> builder = ImmutableList.builder();
  String superClassName = superClassSymbol.getClassBinaryName();
  if (classDumper.isSystemClass(superClassName)) {
    return ImmutableList.of();
  }

  try {
    String className = classFile.getBinaryName();
    JavaClass implementingClass = classDumper.loadJavaClass(className);
    if (implementingClass.isAbstract()) {
      return ImmutableList.of();
    }

    JavaClass superClass = classDumper.loadJavaClass(superClassName);
    if (!superClass.isAbstract()) {
      return ImmutableList.of();
    }

    JavaClass abstractClass = superClass;

    // Equality of BCEL's Method class is on its name and descriptor field
    Set<Method> implementedMethods = new HashSet<>();
    implementedMethods.addAll(ImmutableList.copyOf(implementingClass.getMethods()));

    while (abstractClass.isAbstract()) {
      for (Method abstractMethod : abstractClass.getMethods()) {
        if (!abstractMethod.isAbstract()) {
          // This abstract method has implementation. Subclass does not have to implement it.
          implementedMethods.add(abstractMethod);
        } else if (!implementedMethods.contains(abstractMethod)) {
          String unimplementedMethodName = abstractMethod.getName();
          String unimplementedMethodDescriptor = abstractMethod.getSignature();

          MethodSymbol missingMethodOnClass =
              new MethodSymbol(
                  className, unimplementedMethodName, unimplementedMethodDescriptor, false);
          builder.add(
              new SymbolProblem(missingMethodOnClass, ErrorType.ABSTRACT_METHOD, classFile));
        }
      }
      abstractClass = abstractClass.getSuperClass();
    }
  } catch (ClassNotFoundException ex) {
    // Missing classes are reported by findSymbolProblem method.
  }
  return builder.build();
}
 
Example 9
Source File: InnerClassAccessMap.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Return a map of inner-class member access method names to the fields that
 * they access for given class name.
 *
 * @param className
 *            the name of the class
 * @return map of access method names to the fields they access
 */
private Map<String, InnerClassAccess> getAccessMapForClass(String className) throws ClassNotFoundException {

    Map<String, InnerClassAccess> map = classToAccessMap.get(className);
    if (map == null) {
        map = new HashMap<>(3);

        if (!className.startsWith("[")) {
            JavaClass javaClass = Repository.lookupClass(className);

            Method[] methodList = javaClass.getMethods();
            for (Method method : methodList) {
                String methodName = method.getName();
                if (!methodName.startsWith("access$")) {
                    continue;
                }

                Code code = method.getCode();
                if (code == null) {
                    continue;
                }

                if (DEBUG) {
                    System.out.println("Analyzing " + className + "." + method.getName()
                            + " as an inner-class access method...");
                }

                byte[] instructionList = code.getCode();
                String methodSig = method.getSignature();
                InstructionCallback callback = new InstructionCallback(javaClass, methodName, methodSig, instructionList);
                //                    try {
                new BytecodeScanner().scan(instructionList, callback);
                //                    } catch (LookupFailure lf) {
                //                        throw lf.getException();
                //                    }
                InnerClassAccess access = callback.getAccess();
                if (DEBUG) {
                    System.out.println((access != null ? "IS" : "IS NOT") + " an inner-class access method");
                }
                if (access != null) {
                    map.put(methodName, access);
                }
            }
        }

        if (map.size() == 0) {
            map = Collections.emptyMap();
        } else {
            map = new HashMap<>(map);
        }

        classToAccessMap.put(className, map);
    }

    return map;
}
 
Example 10
Source File: ClassContext.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
public String getFullyQualifiedMethodName(Method method) {
    return getClassDescriptor().getDottedClassName() + "." + method.getName() + method.getSignature();
}
 
Example 11
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 4 votes vote down vote up
protected String makeMethodName(final String className, final Method method) {
  return className + '.' + method.getName() + '.' + method.getSignature();
}
 
Example 12
Source File: Pass2Verifier.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures that <B>final</B> methods are not overridden.
 * <B>Precondition to run this method:
 * constant_pool_entries_satisfy_static_constraints() and
 * every_class_has_an_accessible_superclass() have to be invoked before
 * (in that order).</B>
 *
 * @throws ClassConstraintException otherwise.
 * @see #constant_pool_entries_satisfy_static_constraints()
 * @see #every_class_has_an_accessible_superclass()
 */
private void final_methods_are_not_overridden() {
    try {
    final Map<String, String> hashmap = new HashMap<>();
    JavaClass jc = Repository.lookupClass(myOwner.getClassName());

    int supidx = -1;
    while (supidx != 0) {
        supidx = jc.getSuperclassNameIndex();

        final Method[] methods = jc.getMethods();
        for (final Method method : methods) {
            final String nameAndSig = method.getName() + method.getSignature();

            if (hashmap.containsKey(nameAndSig)) {
                if (method.isFinal()) {
                    if (!(method.isPrivate())) {
                        throw new ClassConstraintException("Method '" + nameAndSig + "' in class '" + hashmap.get(nameAndSig) +
                            "' overrides the final (not-overridable) definition in class '" + jc.getClassName() + "'.");
                    }
                    addMessage("Method '" + nameAndSig + "' in class '" + hashmap.get(nameAndSig) +
                        "' overrides the final (not-overridable) definition in class '" + jc.getClassName() +
                        "'. This is okay, as the original definition was private; however this constraint leverage"+
                        " was introduced by JLS 8.4.6 (not vmspec2) and the behavior of the Sun verifiers.");
                } else {
                    if (!method.isStatic()) { // static methods don't inherit
                        hashmap.put(nameAndSig, jc.getClassName());
                    }
                }
            } else {
                if (!method.isStatic()) { // static methods don't inherit
                    hashmap.put(nameAndSig, jc.getClassName());
                }
            }
        }

        jc = Repository.lookupClass(jc.getSuperclassName());
        // Well, for OBJECT this returns OBJECT so it works (could return anything but must not throw an Exception).
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: this might not be the best way to handle missing classes.
    throw new AssertionViolatedException("Missing class: " + e, e);
    }

}
 
Example 13
Source File: MethodHTML.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
private void writeMethod( final Method method, final int method_number ) {
    // Get raw signature
    final String signature = method.getSignature();
    // Get array of strings containing the argument types
    final String[] args = Utility.methodSignatureArgumentTypes(signature, false);
    // Get return type string
    final String type = Utility.methodSignatureReturnType(signature, false);
    // Get method name
    final String name = method.getName();
    String html_name;
    // Get method's access flags
    String access = Utility.accessToString(method.getAccessFlags());
    // Get the method's attributes, the Code Attribute in particular
    final Attribute[] attributes = method.getAttributes();
    /* HTML doesn't like names like <clinit> and spaces are places to break
     * lines. Both we don't want...
     */
    access = Utility.replace(access, " ", "&nbsp;");
    html_name = Class2HTML.toHTML(name);
    file.print("<TR VALIGN=TOP><TD><FONT COLOR=\"#FF0000\"><A NAME=method" + method_number
            + ">" + access + "</A></FONT></TD>");
    file.print("<TD>" + Class2HTML.referenceType(type) + "</TD><TD>" + "<A HREF=" + className
            + "_code.html#method" + method_number + " TARGET=Code>" + html_name
            + "</A></TD>\n<TD>(");
    for (int i = 0; i < args.length; i++) {
        file.print(Class2HTML.referenceType(args[i]));
        if (i < args.length - 1) {
            file.print(", ");
        }
    }
    file.print(")</TD></TR>");
    // Check for thrown exceptions
    for (int i = 0; i < attributes.length; i++) {
        attribute_html.writeAttribute(attributes[i], "method" + method_number + "@" + i,
                method_number);
        final byte tag = attributes[i].getTag();
        if (tag == Const.ATTR_EXCEPTIONS) {
            file.print("<TR VALIGN=TOP><TD COLSPAN=2></TD><TH ALIGN=LEFT>throws</TH><TD>");
            final int[] exceptions = ((ExceptionTable) attributes[i]).getExceptionIndexTable();
            for (int j = 0; j < exceptions.length; j++) {
                file.print(constantHtml.referenceConstant(exceptions[j]));
                if (j < exceptions.length - 1) {
                    file.print(", ");
                }
            }
            file.println("</TD></TR>");
        } else if (tag == Const.ATTR_CODE) {
            final Attribute[] c_a = ((Code) attributes[i]).getAttributes();
            for (int j = 0; j < c_a.length; j++) {
                attribute_html.writeAttribute(c_a[j], "method" + method_number + "@" + i + "@"
                        + j, method_number);
            }
        }
    }
}
 
Example 14
Source File: BugInstance.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Add a method annotation. If this is the first method annotation added, it
 * becomes the primary method annotation. If the method has source line
 * information, then a SourceLineAnnotation is added to the method.
 *
 * @param javaClass
 *            the class the method is defined in
 * @param method
 *            the method
 * @return this object
 */
@Nonnull
public BugInstance addMethod(JavaClass javaClass, Method method) {
    MethodAnnotation methodAnnotation = new MethodAnnotation(javaClass.getClassName(), method.getName(),
            method.getSignature(), method.isStatic());
    SourceLineAnnotation methodSourceLines = SourceLineAnnotation.forEntireMethod(javaClass, method);
    methodAnnotation.setSourceLines(methodSourceLines);
    addMethod(methodAnnotation);
    return this;
}
 
Example 15
Source File: XFactory.java    From spotbugs with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Create an XMethod object from a BCEL Method.
 *
 * @param className
 *            the class to which the Method belongs
 * @param method
 *            the Method
 * @return an XMethod representing the Method
 */

public static XMethod createXMethod(String className, Method method) {
    String methodName = method.getName();
    String methodSig = method.getSignature();
    int accessFlags = method.getAccessFlags();

    return createXMethod(className, methodName, methodSig, accessFlags);
}
 
Example 16
Source File: ClassParserUsingBCEL.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * @param obj
 *            the method to parse
 * @return a descriptor for the method
 */
protected MethodDescriptor parseMethod(Method obj) {
    return new MethodDescriptor(slashedClassName, obj.getName(), obj.getSignature(), obj.isStatic());
}