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

The following examples show how to use org.apache.bcel.classfile.JavaClass#getInterfaceNames() . 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: JasminVisitor.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
@Override
public void visitJavaClass(final JavaClass clazz) {
    out.println(";; Produced by JasminVisitor (BCEL)");
    out.println(";; https://commons.apache.org/bcel/");
    out.println(";; " + new Date() + "\n");

    out.println(".source " + clazz.getSourceFileName());
    out.println("." + Utility.classOrInterface(clazz.getAccessFlags()) + " " +
            Utility.accessToString(clazz.getAccessFlags(), true) +
            " " + clazz.getClassName().replace('.', '/'));
    out.println(".super " + clazz.getSuperclassName().replace('.', '/'));

    for (final String iface : clazz.getInterfaceNames()) {
        out.println(".implements " + iface.replace('.', '/'));
    }

    out.print("\n");
}
 
Example 2
Source File: LinkageChecker.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns an {@code Optional} describing the symbol problem in the parent classes or interfaces
 * of {@code baseClassName}, if any of them are missing; otherwise an empty {@code Optional}.
 */
private Optional<SymbolProblem> findParentSymbolProblem(String baseClassName) {
  Queue<String> queue = new ArrayDeque<>();
  queue.add(baseClassName);
  while (!queue.isEmpty()) {
    String className = queue.remove();
    if (Object.class.getName().equals(className)) {
      continue; // java.lang.Object is the root of the inheritance tree
    }
    String potentiallyMissingClassName = className;
    try {
      JavaClass baseClass = classDumper.loadJavaClass(className);
      queue.add(baseClass.getSuperclassName());

      for (String interfaceName : baseClass.getInterfaceNames()) {
        potentiallyMissingClassName = interfaceName;
        JavaClass interfaceClass = classDumper.loadJavaClass(interfaceName);
        // An interface may implement other interfaces
        queue.addAll(Arrays.asList(interfaceClass.getInterfaceNames()));
      }
    } catch (ClassNotFoundException ex) {
      // potentiallyMissingClassName (either className or interfaceName) is missing
      SymbolProblem problem =
          new SymbolProblem(
              new ClassSymbol(potentiallyMissingClassName), ErrorType.SYMBOL_NOT_FOUND, null);
      return Optional.of(problem);
    }
  }
  return Optional.empty();
}
 
Example 3
Source File: NoteAnnotationRetention.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitAfter(JavaClass obj) {
    for (String i : obj.getInterfaceNames()) {
        if ("java.lang.annotation.Annotation".equals(i)) {
            AnalysisContext.currentAnalysisContext().getAnnotationRetentionDatabase()
                    .setRuntimeRetention(getDottedClassName(), runtimeRetention);
        }
    }

}
 
Example 4
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitJavaClass(JavaClass obj) {
    if (BCELUtil.isSynthetic(obj)) {
        return;
    }
    String name = obj.getClassName();
    if (!visited.add(name)) {
        return;
    }

    String superClassName = obj.getSuperclassName();
    if (!Values.DOTTED_JAVA_LANG_OBJECT.equals(name)) {
        if (sameSimpleName(superClassName, name)) {
            bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_SUPERCLASS", HIGH_PRIORITY).addClass(name)
                    .addClass(superClassName));
        }
        for (String interfaceName : obj.getInterfaceNames()) {
            if (sameSimpleName(interfaceName, name)) {
                bugReporter.reportBug(new BugInstance(this, "NM_SAME_SIMPLE_NAME_AS_INTERFACE", NORMAL_PRIORITY).addClass(
                        name).addClass(interfaceName));
            }
        }
    }
    if (obj.isInterface()) {
        return;
    }

    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClassName) && !visited.contains(superClassName)) {
        try {
            visitJavaClass(obj.getSuperClass());
        } catch (ClassNotFoundException e) {
            // ignore it
        }
    }
    super.visitJavaClass(obj);
}
 
Example 5
Source File: RedundantInterfaces.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass obj = classContext.getJavaClass();

    String superClassName = obj.getSuperclassName();
    if (Values.DOTTED_JAVA_LANG_OBJECT.equals(superClassName)) {
        return;
    }

    String[] interfaceNames = obj.getInterfaceNames();
    if ((interfaceNames == null) || (interfaceNames.length == 0)) {
        return;
    }

    try {
        JavaClass superObj = obj.getSuperClass();
        SortedSet<String> redundantInfNames = new TreeSet<>();

        for (String interfaceName : interfaceNames) {
            if (!"java.io.Serializable".equals(interfaceName)) {
                JavaClass inf = Repository.lookupClass(interfaceName);
                if (superObj.instanceOf(inf)) {
                    redundantInfNames.add(inf.getClassName());
                }
            }
        }

        if (redundantInfNames.size() > 0) {
            BugInstance bug = new BugInstance(this, "RI_REDUNDANT_INTERFACES", LOW_PRIORITY).addClass(obj);
            for (String redundantInfName : redundantInfNames) {
                bug.addClass(redundantInfName).describe("INTERFACE_TYPE");
            }

            bugReporter.reportBug(bug);
        }

    } catch (ClassNotFoundException cnfe) {
        bugReporter.reportMissingClass(cnfe);
    }
}
 
Example 6
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 7
Source File: ClassDumper.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
private static SymbolReferences.Builder findSymbolReferences(
    ClassFile source, JavaClass javaClass) {
  SymbolReferences.Builder builder = new SymbolReferences.Builder();

  ConstantPool constantPool = javaClass.getConstantPool();
  Constant[] constants = constantPool.getConstantPool();
  for (Constant constant : constants) {
    if (constant == null) {
       continue;
    }

    byte constantTag = constant.getTag();
    switch (constantTag) {
      case Const.CONSTANT_Class:
        ConstantClass constantClass = (ConstantClass) constant;
        ClassSymbol classSymbol = makeSymbol(constantClass, constantPool, javaClass);
        // skip array class because it is provided by runtime
        if (classSymbol.getClassBinaryName().startsWith("[")) {
          break;
        }
        builder.addClassReference(source, classSymbol);
        break;
      case Const.CONSTANT_Methodref:
      case Const.CONSTANT_InterfaceMethodref:
        // Both ConstantMethodref and ConstantInterfaceMethodref are subclass of ConstantCP
        ConstantCP constantMethodref = (ConstantCP) constant;
        builder.addMethodReference(source, makeSymbol(constantMethodref, constantPool));
        break;
      case Const.CONSTANT_Fieldref:
        ConstantFieldref constantFieldref = (ConstantFieldref) constant;
        builder.addFieldReference(source, makeSymbol(constantFieldref, constantPool));
        break;
      default:
        break;
    }
  }

  for (String interfaceName : javaClass.getInterfaceNames()) {
    builder.addClassReference(source, new InterfaceSymbol(interfaceName));
  }

  return builder;
}
 
Example 8
Source File: UnreadFields.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    data.calledFromConstructors.clear();
    hasNativeMethods = false;
    sawSelfCallInConstructor = false;
    publicOrProtectedConstructor = false;
    isSerializable = false;
    if (obj.isAbstract()) {
        data.abstractClasses.add(getDottedClassName());
    } else {
        String superClass = obj.getSuperclassName();
        if (superClass != null) {
            data.hasNonAbstractSubClass.add(superClass);
        }
    }
    data.classesScanned.add(getDottedClassName());
    boolean superClassIsObject = Values.DOTTED_JAVA_LANG_OBJECT.equals(obj.getSuperclassName());
    if (getSuperclassName().indexOf('$') >= 0 || getSuperclassName().indexOf('+') >= 0
            || withinAnonymousClass.matcher(getDottedClassName()).find()) {
        // System.out.println("hicfsc: " + betterClassName);
        data.innerClassCannotBeStatic.add(getDottedClassName());
        // System.out.println("hicfsc: " + betterSuperclassName);
        data.innerClassCannotBeStatic.add(getDottedSuperclassName());
    }
    // Does this class directly implement Serializable?
    String[] interface_names = obj.getInterfaceNames();
    for (String interface_name : interface_names) {
        if ("java.io.Externalizable".equals(interface_name)) {
            isSerializable = true;
        } else if ("java.io.Serializable".equals(interface_name)) {
            isSerializable = true;
            break;
        }
    }

    // Does this class indirectly implement Serializable?
    if ((!superClassIsObject || interface_names.length > 0) && !isSerializable) {
        try {
            Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
            ClassDescriptor desc = DescriptorFactory.createClassDescriptor(obj);
            if (subtypes2.getSubtypes(serializable).contains(desc) || subtypes2.getSubtypes(externalizable).contains(desc)
                    || subtypes2.getSubtypes(remote).contains(desc)) {
                isSerializable = true;
            }
        } catch (ClassNotFoundException e) {
            bugReporter.reportMissingClass(e);
        }
    }

    // System.out.println(getDottedClassName() + " is serializable: " +
    // isSerializable);
    super.visit(obj);
}
 
Example 9
Source File: CloneIdiom.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(JavaClass obj) {
    implementsCloneableDirectly = false;
    invokesSuperClone = false;
    cloneOnlyThrowsException = false;
    isCloneable = false;
    check = false;
    isFinal = obj.isFinal();
    if (obj.isInterface()) {
        return;
    }
    if (obj.isAbstract()) {
        return;
    }
    // Does this class directly implement Cloneable?
    String[] interface_names = obj.getInterfaceNames();
    for (String interface_name : interface_names) {
        if ("java.lang.Cloneable".equals(interface_name)) {
            implementsCloneableDirectly = true;
            isCloneable = true;
            break;
        }
    }

    Subtypes2 subtypes2 = AnalysisContext.currentAnalysisContext().getSubtypes2();
    try {
        if (subtypes2.isSubtype(getClassDescriptor(), cloneDescriptor)) {
            isCloneable = true;
        }
        if (subtypes2.isSubtype(DescriptorFactory.createClassDescriptorFromDottedClassName(obj.getSuperclassName()),
                cloneDescriptor)) {
            implementsCloneableDirectly = false;
        }

    } catch (ClassNotFoundException e) {
        bugReporter.reportMissingClass(e);
    }

    hasCloneMethod = false;
    referencesCloneMethod = false;
    check = true;
    super.visit(obj);
}
 
Example 10
Source File: ClassFilePreDecompilationScan.java    From windup with Eclipse Public License 1.0 4 votes vote down vote up
private void addClassFileMetadata(GraphRewrite event, EvaluationContext context, JavaClassFileModel javaClassFileModel)
{
    try (FileInputStream fis = new FileInputStream(javaClassFileModel.getFilePath()))
    {
        final ClassParser parser = new ClassParser(fis, javaClassFileModel.getFilePath());
        final JavaClass bcelJavaClass = parser.parse();
        final String packageName = bcelJavaClass.getPackageName();

        final String qualifiedName = bcelJavaClass.getClassName();

        final JavaClassService javaClassService = new JavaClassService(event.getGraphContext());
        final JavaClassModel javaClassModel = javaClassService.create(qualifiedName);
        int majorVersion = bcelJavaClass.getMajor();
        int minorVersion = bcelJavaClass.getMinor();

        String simpleName = qualifiedName;
        if (packageName != null && !packageName.isEmpty() && simpleName != null)
        {
            simpleName = StringUtils.substringAfterLast(simpleName, ".");
        }

        javaClassFileModel.setMajorVersion(majorVersion);
        javaClassFileModel.setMinorVersion(minorVersion);
        javaClassFileModel.setPackageName(packageName);

        javaClassModel.setSimpleName(simpleName);
        javaClassModel.setPackageName(packageName);
        javaClassModel.setQualifiedName(qualifiedName);
        javaClassModel.setClassFile(javaClassFileModel);
        javaClassModel.setPublic(bcelJavaClass.isPublic());
        javaClassModel.setInterface(bcelJavaClass.isInterface());

        final String[] interfaceNames = bcelJavaClass.getInterfaceNames();
        if (interfaceNames != null)
        {
            for (final String interfaceName : interfaceNames)
            {
                JavaClassModel interfaceModel = javaClassService.getOrCreatePhantom(interfaceName);
                javaClassService.addInterface(javaClassModel, interfaceModel);
            }
        }

        String superclassName = bcelJavaClass.getSuperclassName();
        if (!bcelJavaClass.isInterface() && !StringUtils.isBlank(superclassName))
            javaClassModel.setExtends(javaClassService.getOrCreatePhantom(superclassName));

        javaClassFileModel.setJavaClass(javaClassModel);
    }
    catch (Exception ex)
    {
        String nl = ex.getMessage() != null ? Util.NL + "\t" : " ";
        final String message = "BCEL was unable to parse class file '" + javaClassFileModel.getFilePath() + "':" + nl + ex.toString();
        LOG.log(Level.WARNING, message);
        ClassificationService classificationService = new ClassificationService(event.getGraphContext());
        classificationService.attachClassification(event, context, javaClassFileModel, UNPARSEABLE_CLASS_CLASSIFICATION, UNPARSEABLE_CLASS_DESCRIPTION);
        javaClassFileModel.setParseError(message);
        javaClassFileModel.setSkipDecompilation(true);
    }
}