Java Code Examples for org.apache.bcel.classfile.JavaClass#getClassName()

The following examples show how to use org.apache.bcel.classfile.JavaClass#getClassName() . 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: ClassDumper.java    From cloud-opensource-java with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a map from classes to the symbol references they contain.
 */
SymbolReferences findSymbolReferences() throws IOException {
  SymbolReferences.Builder builder = new SymbolReferences.Builder();

  for (ClassPathEntry jar : inputClassPath) {
    for (JavaClass javaClass : listClasses(jar)) {
      if (isCompatibleClassFileVersion(javaClass)) {
        String className = javaClass.getClassName();
        // In listClasses(jar), ClassPathRepository creates JavaClass through the first JAR file
        // that contains the class. It may be different from "jar" for an overlapping class.
        ClassFile source = new ClassFile(findClassLocation(className), className);
        builder.addAll(findSymbolReferences(source, javaClass));
      }
    }
  }

  return builder.build();
}
 
Example 2
Source File: RootBuilder.java    From android-classyshark with Apache License 2.0 6 votes vote down vote up
private ClassNode fillFromJar(File file) {

        ClassNode rootNode = new ClassNode(file.getName());
        try {
            JarFile theJar = new JarFile(file);
            Enumeration<? extends JarEntry> en = theJar.entries();

            while (en.hasMoreElements()) {
                JarEntry entry = en.nextElement();
                if (entry.getName().endsWith(".class")) {
                    ClassParser cp = new ClassParser(
                            theJar.getInputStream(entry), entry.getName());
                    JavaClass jc = cp.parse();
                    ClassInfo classInfo = new ClassInfo(jc.getClassName(),
                            jc.getMethods().length);
                    rootNode.add(classInfo);
                }
            }
        } catch (IOException e) {
            System.err.println("Error reading file: " + file + ". " + e.getMessage());
            e.printStackTrace(System.err);
        }

        return rootNode;
    }
 
Example 3
Source File: Pass3aVerifier.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/** Checks if the constraints of operands of the said instruction(s) are satisfied. */
@Override
public void visitGETSTATIC(final GETSTATIC o) {
    try {
    final String field_name = o.getFieldName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
            f = field;
            break;
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    if (! (f.isStatic())) {
        constraintViolated(o, "Referenced field '"+f+"' is not static which it should be.");
    }
    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 4
Source File: BadlyOverriddenAdapter.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    try {
        methodMap.clear();
        badOverrideMap.clear();
        JavaClass superClass = obj.getSuperClass();
        if (superClass == null) {
            return;
        }
        String packageName = superClass.getPackageName();
        String className = superClass.getClassName();

        // A more generic way to add Adapters would be nice here
        isAdapter = ((className.endsWith("Adapter")) && ("java.awt.event".equals(packageName) || "javax.swing.event".equals(packageName)))
                || (("DefaultHandler".equals(className) && ("org.xml.sax.helpers".equals(packageName))));
        if (isAdapter) {
            Method[] methods = superClass.getMethods();
            for (Method method1 : methods) {
                methodMap.put(method1.getName(), method1.getSignature());
            }
        }
    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
}
 
Example 5
Source File: RejarClassesForAnalysis.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private boolean embeddedNameMismatch(ZipFile zipInputFile, ZipEntry ze) throws IOException {
    InputStream zipIn = zipInputFile.getInputStream(ze);
    String name = ze.getName();
    JavaClass j = new ClassParser(zipIn, name).parse();
    zipIn.close();
    String className = j.getClassName();
    String computedFileName = ClassName.toSlashedClassName(className) + ".class";
    if (name.charAt(0) == '1') {
        System.out.println(name);
        System.out.println("  " + className);
    }
    if (computedFileName.equals(name)) {
        return false;
    }
    System.out.println("In " + name + " found " + className);
    return true;
}
 
Example 6
Source File: HiddenInheritedFieldCheck.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aJavaClass)
{
    final JavaClass javaClass = (JavaClass) aJavaClass;
    final String className = javaClass.getClassName();
    final JavaClass[] superClasses = javaClass.getSuperClasses();
    final Field[] fields = javaClass.getFields();
    // Check all fields
    for (int i = 0; i < fields.length; i++) {
        final Field field = fields[i];
        // Go through all superclasses
        for (int j = 0; j < superClasses.length; j++) {
            final JavaClass superClass = superClasses[j];
            final String superClassName = superClass.getClassName();
            final Field[] superClassFields = superClass.getFields();
            // Go through the filds of the superclasses
            for (int k = 0; k < superClassFields.length; k++) {
                final Field superClassField = superClassFields[k];
                if (!superClassField.isPrivate() &&
                    superClassField.getName().equals(field.getName()) &&
                    !ignore(className, field)) {
                    log(
                        javaClass,
                        0,
                        "hidden.inherited.field",
                        new Object[] {fields[i], superClassName});
                }
            }
        }
    }
}
 
Example 7
Source File: ClassGen.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize with existing class.
 * @param clazz JavaClass object (e.g. read from file)
 */
public ClassGen(final JavaClass clazz) {
    super(clazz.getAccessFlags());
    classNameIndex = clazz.getClassNameIndex();
    superclass_name_index = clazz.getSuperclassNameIndex();
    className = clazz.getClassName();
    superClassName = clazz.getSuperclassName();
    fileName = clazz.getSourceFileName();
    cp = new ConstantPoolGen(clazz.getConstantPool());
    major = clazz.getMajor();
    minor = clazz.getMinor();
    final Attribute[] attributes = clazz.getAttributes();
    // J5TODO: Could make unpacking lazy, done on first reference
    final AnnotationEntryGen[] annotations = unpackAnnotations(attributes);
    final Method[] methods = clazz.getMethods();
    final Field[] fields = clazz.getFields();
    final String[] interfaces = clazz.getInterfaceNames();
    for (final String interface1 : interfaces) {
        addInterface(interface1);
    }
    for (final Attribute attribute : attributes) {
        if (!(attribute instanceof Annotations)) {
            addAttribute(attribute);
        }
    }
    for (final AnnotationEntryGen annotation : annotations) {
        addAnnotationEntry(annotation);
    }
    for (final Method method : methods) {
        addMethod(method);
    }
    for (final Field field : fields) {
        addField(field);
    }
}
 
Example 8
Source File: HiddenInheritedFieldCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aJavaClass)
{
    final JavaClass javaClass = (JavaClass) aJavaClass;
    final String className = javaClass.getClassName();
    final JavaClass[] superClasses = javaClass.getSuperClasses();
    final Field[] fields = javaClass.getFields();
    // Check all fields
    for (int i = 0; i < fields.length; i++) {
        final Field field = fields[i];
        // Go through all superclasses
        for (int j = 0; j < superClasses.length; j++) {
            final JavaClass superClass = superClasses[j];
            final String superClassName = superClass.getClassName();
            final Field[] superClassFields = superClass.getFields();
            // Go through the filds of the superclasses
            for (int k = 0; k < superClassFields.length; k++) {
                final Field superClassField = superClassFields[k];
                if (!superClassField.isPrivate() &&
                    superClassField.getName().equals(field.getName()) &&
                    !ignore(className, field)) {
                    log(
                        javaClass,
                        0,
                        "hidden.inherited.field",
                        new Object[] {fields[i], superClassName});
                }
            }
        }
    }
}
 
Example 9
Source File: StaticCalendarDetector.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Remembers the class name and resets temporary fields.
 */
@Override
public void visit(JavaClass someObj) {
    currentClass = someObj.getClassName();
    currentMethod = null;
    currentCFG = null;
    currentLockDataFlow = null;
    sawDateClass = false;

}
 
Example 10
Source File: MultithreadedInstanceAccess.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    try {
        JavaClass cls = classContext.getJavaClass();
        String superClsName = cls.getSuperclassName();
        if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClsName)) {
            return;
        }

        if (STRUTS_ACTION_NAME.equals(superClsName)) {
            mtClassName = STRUTS_ACTION_NAME;
            super.visitClassContext(classContext);
        } else if (SERVLET_NAME.equals(superClsName)) {
            mtClassName = SERVLET_NAME;
            super.visitClassContext(classContext);
        } else {
            for (JavaClass mtClass : getMtClasses()) {
                /*
                 * note: We could just call cls.instanceOf(mtClass) and it
                 * would work for both classes and interfaces, but if
                 * mtClass is an interface it is more efficient to call
                 * cls.implementationOf() and since we're doing this on each
                 * visit that's what we'll do. also note:
                 * implementationOf(mtClass) throws an
                 * IllegalArgumentException when mtClass is not an
                 * interface. See bug#1428253.
                 */
                if (mtClass.isClass() ? cls.instanceOf(mtClass) : cls.implementationOf(mtClass)) {
                    mtClassName = mtClass.getClassName();
                    super.visitClassContext(classContext);
                    return;
                }
            }
        }
    } catch (Exception e) {
        // already reported
    }
}
 
Example 11
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 12
Source File: InefficientMemberAccess.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass cls = classContext.getJavaClass();
    clsName = cls.getClassName();
    if (clsName.indexOf('$') >= 0) {
        super.visitClassContext(classContext);
    }
}
 
Example 13
Source File: JasminVisitor.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass java_class;

    if (argv.length == 0) {
        System.err.println("disassemble: No input files specified");
        return;
    }

    for (final String arg : argv) {
        if ((java_class = Repository.lookupClass(arg)) == null) {
            java_class = new ClassParser(arg).parse();
        }

        String class_name = java_class.getClassName();
        final int index = class_name.lastIndexOf('.');
        final String path = class_name.substring(0, index + 1).replace('.', File.separatorChar);
        class_name = class_name.substring(index + 1);

        if (!path.equals("")) {
            final File f = new File(path);
            f.mkdirs();
        }

        final String name = path + class_name + ".j";
        final FileOutputStream out = new FileOutputStream(name);
        new JasminVisitor(java_class, out).disassemble();
        System.out.println("File dumped to: " + name);
    }
}
 
Example 14
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 15
Source File: MethodGenFactory.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public MethodGen analyze(IAnalysisCache analysisCache, MethodDescriptor descriptor) throws CheckedAnalysisException {
    Method method = getMethod(analysisCache, descriptor);

    if (method.getCode() == null) {
        return null;
    }
    XMethod xmethod = XFactory.createXMethod(descriptor);
    if (xmethod.usesInvokeDynamic() && false) {
        AnalysisContext.currentAnalysisContext().analysisSkippedDueToInvokeDynamic(xmethod);
        return null;
    }

    try {
        AnalysisContext analysisContext = AnalysisContext.currentAnalysisContext();
        JavaClass jclass = getJavaClass(analysisCache, descriptor.getClassDescriptor());
        ConstantPoolGen cpg = getConstantPoolGen(analysisCache, descriptor.getClassDescriptor());

        String methodName = method.getName();
        int codeLength = method.getCode().getCode().length;
        String superclassName = jclass.getSuperclassName();
        if (codeLength > 6000 && Const.STATIC_INITIALIZER_NAME.equals(methodName) && "java.lang.Enum".equals(superclassName)) {
            analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                    new JavaClassAndMethod(jclass, method).toMethodDescriptor());
            return null;
        }
        if (analysisContext.getBoolProperty(AnalysisFeatures.SKIP_HUGE_METHODS)) {
            if (codeLength > 6000 || (Const.STATIC_INITIALIZER_NAME.equals(methodName) || "getContents".equals(methodName))
                    && codeLength > 2000) {
                analysisContext.getLookupFailureCallback().reportSkippedAnalysis(
                        new JavaClassAndMethod(jclass, method).toMethodDescriptor());
                return null;
            }
        }

        return new MethodGen(method, jclass.getClassName(), cpg);
    } catch (Exception e) {
        AnalysisContext.logError("Error constructing methodGen", e);
        return null;
    }
}
 
Example 16
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitPUTSTATIC(final PUTSTATIC o) {
    try {
    final String field_name = o.getFieldName(cpg);
    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
                final Type f_type = Type.getType(field.getSignature());
              final Type o_type = o.getType(cpg);
                /* TODO: Check if assignment compatibility is sufficient.
               * What does Sun do?
               */
              if (f_type.equals(o_type)) {
                    f = field;
                    break;
                }
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }
    final Type value = stack().peek();
    final Type t = Type.getType(f.getSignature());
    Type shouldbe = t;
    if (shouldbe == Type.BOOLEAN ||
            shouldbe == Type.BYTE ||
            shouldbe == Type.CHAR ||
            shouldbe == Type.SHORT) {
        shouldbe = Type.INT;
    }
    if (t instanceof ReferenceType) {
        ReferenceType rvalue = null;
        if (value instanceof ReferenceType) {
            rvalue = (ReferenceType) value;
            referenceTypeIsInitialized(o, rvalue);
        }
        else{
            constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
        }
        // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
        // using "wider cast object types" created during verification.
        // Comment it out if you encounter problems. See also the analogon at visitPUTFIELD.
        if (!(rvalue.isAssignmentCompatibleWith(shouldbe))) {
            constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
        }
    }
    else{
        if (shouldbe != value) {
            constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
        }
    }
    // TODO: Interface fields may be assigned to only once. (Hard to implement in
    //       JustIce's execution model). This may only happen in <clinit>, see Pass 3a.

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 17
Source File: InstConstraintVisitor.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Ensures the specific preconditions of the said instruction.
 */
@Override
public void visitPUTFIELD(final PUTFIELD o) {
    try {

    final Type objectref = stack().peek(1);
    if (! ( (objectref instanceof ObjectType) || (objectref == Type.NULL) ) ) {
        constraintViolated(o,
            "Stack next-to-top should be an object reference that's not an array reference, but is '"+objectref+"'.");
    }

    final String field_name = o.getFieldName(cpg);

    final JavaClass jc = Repository.lookupClass(getObjectType(o).getClassName());
    final Field[] fields = jc.getFields();
    Field f = null;
    for (final Field field : fields) {
        if (field.getName().equals(field_name)) {
              final Type f_type = Type.getType(field.getSignature());
              final Type o_type = o.getType(cpg);
                /* TODO: Check if assignment compatibility is sufficient.
               * What does Sun do?
               */
              if (f_type.equals(o_type)) {
                    f = field;
                    break;
                }
        }
    }
    if (f == null) {
        throw new AssertionViolatedException("Field '" + field_name + "' not found in " + jc.getClassName());
    }

    final Type value = stack().peek();
    final Type t = Type.getType(f.getSignature());
    Type shouldbe = t;
    if (shouldbe == Type.BOOLEAN ||
            shouldbe == Type.BYTE ||
            shouldbe == Type.CHAR ||
            shouldbe == Type.SHORT) {
        shouldbe = Type.INT;
    }
    if (t instanceof ReferenceType) {
        ReferenceType rvalue = null;
        if (value instanceof ReferenceType) {
            rvalue = (ReferenceType) value;
            referenceTypeIsInitialized(o, rvalue);
        }
        else{
            constraintViolated(o, "The stack top type '"+value+"' is not of a reference type as expected.");
        }
        // TODO: This can possibly only be checked using Staerk-et-al's "set-of-object types", not
        // using "wider cast object types" created during verification.
        // Comment it out if you encounter problems. See also the analogon at visitPUTSTATIC.
        if (!(rvalue.isAssignmentCompatibleWith(shouldbe))) {
            constraintViolated(o, "The stack top type '"+value+"' is not assignment compatible with '"+shouldbe+"'.");
        }
    }
    else{
        if (shouldbe != value) {
            constraintViolated(o, "The stack top type '"+value+"' is not of type '"+shouldbe+"' as expected.");
        }
    }

    if (f.isProtected()) {
        final ObjectType classtype = getObjectType(o);
        final ObjectType curr = ObjectType.getInstance(mg.getClassName());

        if (    classtype.equals(curr) ||
                    curr.subclassOf(classtype)    ) {
            final Type tp = stack().peek(1);
            if (tp == Type.NULL) {
                return;
            }
            if (! (tp instanceof ObjectType) ) {
                constraintViolated(o, "The 'objectref' must refer to an object that's not an array. Found instead: '"+tp+"'.");
            }
            final ObjectType objreftype = (ObjectType) tp;
            if (! ( objreftype.equals(curr) ||
                        objreftype.subclassOf(curr) ) ) {
                constraintViolated(o,
                    "The referenced field has the ACC_PROTECTED modifier, and it's a member of the current class or"+
                    " a superclass of the current class. However, the referenced object type '"+stack().peek()+
                    "' is not the current class or a subclass of the current class.");
            }
        }
    }

    // TODO: Could go into Pass 3a.
    if (f.isStatic()) {
        constraintViolated(o, "Referenced field '"+f+"' is static which it shouldn't be.");
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 18
Source File: HiddenStaticMethodCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aJavaClass)
{
    final JavaClass javaClass = (JavaClass) aJavaClass;
    final String className = javaClass.getClassName();
    final JavaClass[] superClasses = javaClass.getSuperClasses();
    final Method[] methods = javaClass.getMethods();
    // Check all methods
    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        // Check that the method is a possible match
        if (!method.isPrivate() && method.isStatic())  {
            // Go through all their superclasses
            for (int j = 0; j < superClasses.length; j++) {
                final JavaClass superClass = superClasses[j];
                final String superClassName = superClass.getClassName();
                final Method[] superClassMethods = superClass.getMethods();
                // Go through the methods of the superclasses
                for (int k = 0; k < superClassMethods.length; k++) {
                    final Method superClassMethod = superClassMethods[k];
                    if (superClassMethod.getName().equals(method.getName()) &&
                        !ignore(className, method)) {
                        Type[] methodTypes = method.getArgumentTypes();
                        Type[] superTypes = superClassMethod.
                            getArgumentTypes();
                        if (methodTypes.length == superTypes.length) {
                            boolean match = true;
                            for (int arg = 0; arg < methodTypes.length; arg++) {
                                if (!methodTypes[arg].equals(superTypes[arg])) {
                                    match = false;
                                }
                            }
                            // Same method parameters
                            if (match) {
                                log(
                                    javaClass,
                                    0,
                                    "hidden.static.method",
                                    new Object[] {method, superClassName});
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 19
Source File: HiddenStaticMethodCheck.java    From contribution with GNU Lesser General Public License v2.1 4 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void visitObject(Object aJavaClass)
{
    final JavaClass javaClass = (JavaClass) aJavaClass;
    final String className = javaClass.getClassName();
    final JavaClass[] superClasses = javaClass.getSuperClasses();
    final Method[] methods = javaClass.getMethods();
    // Check all methods
    for (int i = 0; i < methods.length; i++) {
        final Method method = methods[i];
        // Check that the method is a possible match
        if (!method.isPrivate() && method.isStatic())  {
            // Go through all their superclasses
            for (int j = 0; j < superClasses.length; j++) {
                final JavaClass superClass = superClasses[j];
                final String superClassName = superClass.getClassName();
                final Method[] superClassMethods = superClass.getMethods();
                // Go through the methods of the superclasses
                for (int k = 0; k < superClassMethods.length; k++) {
                    final Method superClassMethod = superClassMethods[k];
                    if (superClassMethod.getName().equals(method.getName()) &&
                        !ignore(className, method)) {
                        Type[] methodTypes = method.getArgumentTypes();
                        Type[] superTypes = superClassMethod.
                            getArgumentTypes();
                        if (methodTypes.length == superTypes.length) {
                            boolean match = true;
                            for (int arg = 0; arg < methodTypes.length; arg++) {
                                if (!methodTypes[arg].equals(superTypes[arg])) {
                                    match = false;
                                }
                            }
                            // Same method parameters
                            if (match) {
                                log(
                                    javaClass,
                                    0,
                                    "hidden.static.method",
                                    new Object[] {method, superClassName});
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example 20
Source File: FieldAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 2 votes vote down vote up
/**
 * Factory method. Construct from class name and BCEL Field object.
 *
 * @param jClass
 *            the class which defines the field
 * @param field
 *            the BCEL Field object
 * @return the FieldAnnotation
 */
public static FieldAnnotation fromBCELField(JavaClass jClass, Field field) {
    return new FieldAnnotation(jClass.getClassName(), field.getName(), field.getSignature(), field.isStatic());
}