org.apache.bcel.classfile.Field Java Examples

The following examples show how to use org.apache.bcel.classfile.Field. 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: Subtypes2.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static boolean isJSP(JavaClass javaClass) {
    @DottedClassName
    String className = javaClass.getClassName();
    if (className.endsWith("_jsp") || className.endsWith("_tag")) {
        return true;
    }
    for (Method m : javaClass.getMethods()) {
        if (m.getName().startsWith("_jsp")) {
            return true;
        }
    }

    for (Field f : javaClass.getFields()) {
        if (f.getName().startsWith("_jsp")) {
            return true;
        }
    }
    return Subtypes2.instanceOf(className, "javax.servlet.jsp.JspPage")
            || Subtypes2.instanceOf(className, "org.apache.jasper.runtime.HttpJspBase")
            || Subtypes2.instanceOf(className, "javax.servlet.jsp.tagext.SimpleTagSupport")
            || Subtypes2.instanceOf(className, " org.apache.jasper.runtime.JspSourceDependent");
}
 
Example #2
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 6 votes vote down vote up
protected String field2str(final Field field) {
  String modifier = "";

  if (field.isPrivate()) {
    modifier = "private ";
  } else if (field.isProtected()) {
    modifier = "protected ";
  } else if (field.isPublic()) {
    modifier = "public ";
  }

  if (field.isStatic()) {
    modifier += "static ";
  }

  if (field.isFinal()) {
    modifier += "final ";
  }

  modifier += field.getType().toString();

  modifier += ' ' + field.getName();

  return modifier;
}
 
Example #3
Source File: CheckAnalysisContextContainedAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field field) {
    if (!field.isStatic()) {
        return;
    }
    String signature = field.getSignature();
    if (signature.startsWith("Ljava/util/") && !"Ljava/util/regex/Pattern;".equals(signature)
            && !"Ljava/util/logging/Logger;".equals(signature) && !"Ljava/util/BitSet;".equals(signature)
            && !"Ljava/util/ResourceBundle;".equals(signature)
            && !"Ljava/util/Comparator;".equals(signature)
            && getXField().getAnnotation(ConstantAnnotation) == null) {
        boolean flagged = analysisContextContained(getXClass());

        bugReporter.reportBug(new BugInstance(this, "TESTING", flagged ? NORMAL_PRIORITY : LOW_PRIORITY).addClass(this).addField(this).addType(
                signature));

    }
}
 
Example #4
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
@Override
public void visit(Field obj) {
    if (getFieldName().length() == 1) {
        return;
    }

    if (isEclipseNLS) {
        int flags = obj.getAccessFlags();
        if ((flags & Const.ACC_STATIC) != 0 && ((flags & Const.ACC_PUBLIC) != 0) && "Ljava/lang/String;".equals(getFieldSig())) {
            // ignore "public statis String InstallIUCommandTooltip;"
            // messages from Eclipse NLS bundles
            return;
        }
    }
    if (badFieldName(obj)) {
        bugReporter.reportBug(new BugInstance(this, "NM_FIELD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadFieldNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClass(this).addVisitedField(this));
    }
}
 
Example #5
Source File: id.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] argv) throws Exception {
    JavaClass clazz;

    if ((clazz = Repository.lookupClass(argv[0])) == null) {
        clazz = new ClassParser(argv[0]).parse(); // May throw IOException
    }

    final ClassGen cg = new ClassGen(clazz);

    for (final Method method : clazz.getMethods()) {
        final MethodGen mg = new MethodGen(method, cg.getClassName(), cg.getConstantPool());
        cg.replaceMethod(method, mg.getMethod());
    }

    for (final Field field : clazz.getFields()) {
        final FieldGen fg = new FieldGen(field, cg.getConstantPool());
        cg.replaceField(field, fg.getField());
    }

    cg.getJavaClass().dump(clazz.getClassName() + ".clazz");
}
 
Example #6
Source File: ClassDumper.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Processes information about the fields of the class, i.e., its variables.
 * @throws  IOException
 * @throws  ClassFormatException
 */
private final void processFields () throws IOException, ClassFormatException {
    int fields_count;
    fields_count = file.readUnsignedShort();
    fields = new Field[fields_count];

    // sometimes fields[0] is magic used for serialization
    System.out.printf("%nFields(%d):%n", fields_count);

    for (int i = 0; i < fields_count; i++) {
        processFieldOrMethod();
        if (i < fields_count - 1) {
            System.out.println();
        }
    }
}
 
Example #7
Source File: FieldGen.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate from existing field.
 *
 * @param field Field object
 * @param cp constant pool (must contain the same entries as the field's constant pool)
 */
public FieldGen(final Field field, final ConstantPoolGen cp) {
    this(field.getAccessFlags(), Type.getType(field.getSignature()), field.getName(), cp);
    final Attribute[] attrs = field.getAttributes();
    for (final Attribute attr : attrs) {
        if (attr instanceof ConstantValue) {
            setValue(((ConstantValue) attr).getConstantValueIndex());
        } else if (attr instanceof Annotations) {
            final Annotations runtimeAnnotations = (Annotations)attr;
            final AnnotationEntry[] annotationEntries = runtimeAnnotations.getAnnotationEntries();
            for (final AnnotationEntry element : annotationEntries) {
                addAnnotationEntry(new AnnotationEntryGen(element,cp,false));
            }
        } else {
            addAttribute(attr);
        }
    }
}
 
Example #8
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 6 votes vote down vote up
protected Field[] getFields(final ClassItem classItem, final boolean staticFields) {
  final Set<Field> fieldSet = new TreeSet<Field>(new Comparator<Field>() {

    @Override
    public int compare(final Field o1, final Field o2) {
      return o1.getName().compareTo(o2.getName());
    }
  });

  final Field[] fields = classItem.getJavaClass().getFields();
  for (final Field field : fields) {
    if (staticFields) {
      if (field.isStatic()) {
        fieldSet.add(field);
      }
    } else {
      if (!field.isStatic()) {
        fieldSet.add(field);
      }
    }
  }

  return fieldSet.toArray(new Field[fieldSet.size()]);
}
 
Example #9
Source File: Hierarchy.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Find a field with given name defined in given class.
 *
 * @param className
 *            the name of the class
 * @param fieldName
 *            the name of the field
 * @return the Field, or null if no such field could be found
 */
public static Field findField(String className, String fieldName) throws ClassNotFoundException {
    JavaClass jclass = Repository.lookupClass(className);

    while (jclass != null) {
        Field[] fieldList = jclass.getFields();
        for (Field field : fieldList) {
            if (field.getName().equals(fieldName)) {
                return field;
            }
        }

        jclass = jclass.getSuperClass();
    }

    return null;
}
 
Example #10
Source File: MethodHTML.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
MethodHTML(final String dir, final String class_name, final Method[] methods, final Field[] fields,
        final ConstantHTML constant_html, final AttributeHTML attribute_html) throws IOException {
    this.className = class_name;
    this.attribute_html = attribute_html;
    this.constantHtml = constant_html;
    file = new PrintWriter(new FileOutputStream(dir + class_name + "_methods.html"));
    file.println("<HTML><BODY BGCOLOR=\"#C0C0C0\"><TABLE BORDER=0>");
    file.println("<TR><TH ALIGN=LEFT>Access&nbsp;flags</TH><TH ALIGN=LEFT>Type</TH>"
            + "<TH ALIGN=LEFT>Field&nbsp;name</TH></TR>");
    for (final Field field : fields) {
        writeField(field);
    }
    file.println("</TABLE>");
    file.println("<TABLE BORDER=0><TR><TH ALIGN=LEFT>Access&nbsp;flags</TH>"
            + "<TH ALIGN=LEFT>Return&nbsp;type</TH><TH ALIGN=LEFT>Method&nbsp;name</TH>"
            + "<TH ALIGN=LEFT>Arguments</TH></TR>");
    for (int i = 0; i < methods.length; i++) {
        writeMethod(methods[i], i);
    }
    file.println("</TABLE></BODY></HTML>");
    file.close();
}
 
Example #11
Source File: ClassGen.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * @return the (finally) built up Java class object.
 */
public JavaClass getJavaClass() {
    final int[] interfaces = getInterfaces();
    final Field[] fields = getFields();
    final Method[] methods = getMethods();
    Attribute[] attributes = null;
    if (annotationList.isEmpty()) {
        attributes = getAttributes();
    } else {
        // TODO: Sometime later, trash any attributes called 'RuntimeVisibleAnnotations' or 'RuntimeInvisibleAnnotations'
        final Attribute[] annAttributes  = AnnotationEntryGen.getAnnotationAttributes(cp, getAnnotationEntries());
        attributes = new Attribute[attributeList.size()+annAttributes.length];
        attributeList.toArray(attributes);
        System.arraycopy(annAttributes,0,attributes,attributeList.size(),annAttributes.length);
    }
    // Must be last since the above calls may still add something to it
    final ConstantPool _cp = this.cp.getFinalConstantPool();
    return new JavaClass(classNameIndex, superclass_name_index, fileName, major, minor,
            super.getAccessFlags(), _cp, interfaces, fields, methods, attributes);
}
 
Example #12
Source File: UnreadFieldCheck.java    From contribution with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClasses)
{
    final Iterator it = aJavaClasses.iterator();
    while (it.hasNext()) {
        final JavaClass javaClass = (JavaClass) it.next();
        final String className = javaClass.getClassName();
        final JavaClassDefinition classDef = findJavaClassDef(javaClass);
        final FieldDefinition[] fieldDefs = classDef.getFieldDefs();
        for (int i = 0; i < fieldDefs.length; i++) {
            if (fieldDefs[i].getReadReferenceCount() == 0) {
                final Field field = fieldDefs[i].getField();
                if (!field.isFinal()
                    && (!ignore(className, field))
                    )
                {
                    log(
                        javaClass,
                        0,
                        "unread.field",
                        new Object[] {fieldDefs[i]});
                }
            }
        }
    }
}
 
Example #13
Source File: MethodHTML.java    From commons-bcel with Apache License 2.0 6 votes vote down vote up
/**
 * Print field of class.
 *
 * @param field field to print
 * @throws java.io.IOException
 */
private void writeField( final Field field ) throws IOException {
    final String type = Utility.signatureToString(field.getSignature());
    final String name = field.getName();
    String access = Utility.accessToString(field.getAccessFlags());
    Attribute[] attributes;
    access = Utility.replace(access, " ", "&nbsp;");
    file.print("<TR><TD><FONT COLOR=\"#FF0000\">" + access + "</FONT></TD>\n<TD>"
            + Class2HTML.referenceType(type) + "</TD><TD><A NAME=\"field" + name + "\">" + name
            + "</A></TD>");
    attributes = field.getAttributes();
    // Write them to the Attributes.html file with anchor "<name>[<i>]"
    for (int i = 0; i < attributes.length; i++) {
        attribute_html.writeAttribute(attributes[i], name + "@" + i);
    }
    for (int i = 0; i < attributes.length; i++) {
        if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // Default value
            final String str = ((ConstantValue) attributes[i]).toString();
            // Reference attribute in _attributes.html
            file.print("<TD>= <A HREF=\"" + className + "_attributes.html#" + name + "@" + i
                    + "\" TARGET=\"Attributes\">" + str + "</TD>\n");
            break;
        }
    }
    file.println("</TR>");
}
 
Example #14
Source File: PreorderVisitor.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void doVisitField(Field field) {
    if (visitingField) {
        throw new IllegalStateException("visitField called when already visiting a field");
    }
    visitingField = true;
    this.field = field;
    try {
        fieldName = fieldSig = dottedFieldSig = fullyQualifiedFieldName = null;
        thisFieldInfo = (FieldInfo) thisClassInfo.findField(getFieldName(), getFieldSig(), field.isStatic());
        assert thisFieldInfo != null : "Can't get field info for " + getFullyQualifiedFieldName();
        fieldIsStatic = field.isStatic();
        field.accept(this);
        Attribute[] attributes = field.getAttributes();
        for (Attribute attribute : attributes) {
            attribute.accept(this);
        }
    } finally {
        visitingField = false;
        this.field = null;
        this.thisFieldInfo = null;
    }
}
 
Example #15
Source File: UnreadFieldCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.bcel.IObjectSetVisitor */
public void leaveSet(Set aJavaClasses)
{
    final Iterator it = aJavaClasses.iterator();
    while (it.hasNext()) {
        final JavaClass javaClass = (JavaClass) it.next();
        final String className = javaClass.getClassName();
        final JavaClassDefinition classDef = findJavaClassDef(javaClass);
        final FieldDefinition[] fieldDefs = classDef.getFieldDefs();
        for (int i = 0; i < fieldDefs.length; i++) {
            if (fieldDefs[i].getReadReferenceCount() == 0) {
                final Field field = fieldDefs[i].getField();
                if (!field.isFinal()
                    && (!ignore(className, field))
                    )
                {
                    log(
                        javaClass,
                        0,
                        "unread.field",
                        new Object[] {fieldDefs[i]});
                }
            }
        }
    }
}
 
Example #16
Source File: BetaDetector.java    From google-http-java-client with Apache License 2.0 6 votes vote down vote up
/**
 * Reports bug in case the field defined by the given name is {@link Beta}.
 *
 * <p>The field is searched in current class and all super classses as well.
 */
private void checkField(String fieldName) {
  JavaClass javaClass = checkClass();
  if (javaClass == null) {
    return;
  }

  for (JavaClass current = javaClass; current != null; current = getSuperclass(current)) {
    for (Field field : current.getFields()) {
      if (fieldName.equals(field.getName())) {
        // field has been found - check if it's beta
        if (isBeta(field.getAnnotationEntries())) {
          bugReporter.reportBug(createBugInstance(BETA_FIELD_USAGE).addReferencedField(this));
        }
        return;
      }
    }
  }
  bugReporter.logError("Can't locate field " + javaClass.getClassName() + "." + fieldName);
}
 
Example #17
Source File: UnsafeJacksonDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void analyzeField(Field field, JavaClass javaClass) {
    for (AnnotationEntry annotation : field.getAnnotationEntries())  {
        if (ANNOTATION_TYPES.contains(annotation.getAnnotationType()) ||
                annotation.getAnnotationType().contains("JsonTypeInfo")) {
            for (ElementValuePair elementValuePair : annotation.getElementValuePairs()) {
                if ("use".equals((elementValuePair.getNameString())) &&
                        VULNERABLE_USE_NAMES.contains(elementValuePair.getValue().stringifyValue())) {
                    bugReporter.reportBug(new BugInstance(this, DESERIALIZATION_TYPE, HIGH_PRIORITY)
                            .addClass(javaClass)
                            .addString(javaClass.getClassName() + " on field " +
                                    field.getName() + " of type " + field.getType() +
                                    " annotated with " + annotation.toShortString())
                            .addField(FieldAnnotation.fromBCELField(javaClass, field))
                            .addString("")
                    );
                }
            }
        }
    }
}
 
Example #18
Source File: UnsafeJacksonDeserializationDetector.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public void visitClassContext(ClassContext classContext) {
    JavaClass javaClass = classContext.getJavaClass();
    if (OBJECT_MAPPER_CLASSES.contains(javaClass.getClassName())) {
        return;
    }
    for (Field field : javaClass.getFields()) {
        analyzeField(field, javaClass);
    }
    for (Method m : javaClass.getMethods()) {
        try {
            analyzeMethod(m, classContext);
        }
        catch (CFGBuilderException | DataflowAnalysisException e) {
        }
    }
}
 
Example #19
Source File: FindNoSideEffectMethods.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Field obj) {
    XField xField = getXField();
    if (!xField.isStatic() && (xField.isPrivate() || xField.isFinal()) && xField.isReferenceType()) {
        allowedFields.add(xField.getFieldDescriptor());
    }
}
 
Example #20
Source File: JavaClassDefinition.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Creates a JavaClassDefinition from a JavaClass. The fields and
 * methods of the JavaClassDefinition are those whose scopes are
 * in restricted sets of Scopes.
 * @param aJavaClass the JavaClass for the definition.
 * @param aFieldScopes the restricted set of field scopes.
 * @param aMethodScopes the restriced set of method scopes.
 */
public JavaClassDefinition(
    JavaClass aJavaClass,
    Set aFieldScopes,
    Set aMethodScopes)
{
    mJavaClass = aJavaClass;

    // create method definitions, restricted by scope
    final Method[] methods = aJavaClass.getMethods();
    final Set methodSet = new HashSet();
    mMethodDefs = new MethodDefinition[methods.length];
    for (int i = 0; i < methods.length; i++) {
        if (Utils.inScope(methods[i], aMethodScopes)) {
            methodSet.add(new MethodDefinition(methods[i]));
        }
    }
    mMethodDefs =
        (MethodDefinition[]) methodSet.toArray(
            new MethodDefinition[methodSet.size()]);

    // create field definitions, restricted by scope
    final Field[] fields = aJavaClass.getFields();
    mFieldDefs = new HashMap(fields.length);
    for (int i = 0; i < fields.length; i++) {
        if (Utils.inScope(fields[i], aFieldScopes)) {
            mFieldDefs.put(
                fields[i].getName(),
                new FieldDefinition(fields[i]));
        }
    }
}
 
Example #21
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 #22
Source File: FindMaskedFields.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(LocalVariableTable obj) {
    if (ENABLE_LOCALS) {
        if (staticMethod) {
            return;
        }

        LocalVariable[] vars = obj.getLocalVariableTable();
        // System.out.println("Num params = " + numParms);
        for (LocalVariable var : vars) {
            if (var.getIndex() < numParms) {
                continue;
            }
            String varName = var.getName();
            if ("serialVersionUID".equals(varName)) {
                continue;
            }
            Field f = classFields.get(varName);
            // System.out.println("Checking " + varName);
            // System.out.println(" got " + f);
            // TODO: we could distinguish between obscuring a field in the
            // same class
            // vs. obscuring a field in a superclass. Not sure how important
            // that is.
            if (f != null) {
                FieldAnnotation fa = FieldAnnotation.fromBCELField(getDottedClassName(), f);
                if (true || var.getStartPC() > 0) {
                    bugReporter.reportBug(new BugInstance(this, "MF_METHOD_MASKS_FIELD", LOW_PRIORITY)
                            .addClassAndMethod(this).addField(fa).addSourceLine(this, var.getStartPC() - 1));
                }
            }
        }
    }
    super.visit(obj);
}
 
Example #23
Source File: VisitorSet.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * @see org.apache.bcel.classfile.Visitor
 */
public void visitField(Field aField)
{
    for (Iterator iter = mVisitors.iterator(); iter.hasNext();) {
        IDeepVisitor visitor = (IDeepVisitor) iter.next();
        Visitor v = visitor.getClassFileVisitor();
        aField.accept(v);
    }
}
 
Example #24
Source File: BCELifier.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
@Override
public void visitField( final Field field ) {
    _out.println();
    _out.println("    field = new FieldGen(" + printFlags(field.getAccessFlags()) + ", "
            + printType(field.getSignature()) + ", \"" + field.getName() + "\", _cp);");
    final ConstantValue cv = field.getConstantValue();
    if (cv != null) {
        final String value = cv.toString();
        _out.println("    field.setInitValue(" + value + ")");
    }
    _out.println("    _cg.addField(field.getField());");
}
 
Example #25
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 #26
Source File: ClassFeatureSet.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Initialize from given JavaClass.
 *
 * @param javaClass
 *            the JavaClass
 * @return this object
 */
public ClassFeatureSet initialize(JavaClass javaClass) {
    this.className = javaClass.getClassName();
    this.isInterface = javaClass.isInterface();

    addFeature(CLASS_NAME_KEY + transformClassName(javaClass.getClassName()));

    for (Method method : javaClass.getMethods()) {
        if (!isSynthetic(method)) {
            String transformedMethodSignature = transformMethodSignature(method.getSignature());

            if (method.isStatic() || !overridesSuperclassMethod(javaClass, method)) {
                addFeature(METHOD_NAME_KEY + method.getName() + ":" + transformedMethodSignature);
            }

            Code code = method.getCode();
            if (code != null && code.getCode() != null && code.getCode().length >= MIN_CODE_LENGTH) {
                addFeature(CODE_LENGTH_KEY + method.getName() + ":" + transformedMethodSignature + ":"
                        + code.getCode().length);
            }
        }
    }

    for (Field field : javaClass.getFields()) {
        if (!isSynthetic(field)) {
            addFeature(FIELD_NAME_KEY + field.getName() + ":" + transformSignature(field.getSignature()));
        }
    }

    return this;
}
 
Example #27
Source File: FieldAnnotationsTestCase.java    From commons-bcel with Apache License 2.0 5 votes vote down vote up
public void checkAnnotatedField(final JavaClass clazz, final String fieldname,
        final String AnnotationEntryName, final String AnnotationEntryElementName,
        final String AnnotationEntryElementValue)
{
    final Field[] fields = clazz.getFields();
    for (final Field f : fields) {
        final AnnotationEntry[] fieldAnnotationEntrys = f.getAnnotationEntries();
        if (f.getName().equals(fieldname))
        {
            checkAnnotationEntry(fieldAnnotationEntrys[0], AnnotationEntryName,
                    AnnotationEntryElementName, AnnotationEntryElementValue);
        }
    }
}
 
Example #28
Source File: FindRefComparison.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private void handleLoad(FieldInstruction obj) {
    consumeStack(obj);

    Type type = obj.getType(getCPG());
    if (!STRING_SIGNATURE.equals(type.getSignature())) {
        throw new IllegalArgumentException("type is not String: " + type);
    }
    try {
        String className = obj.getClassName(getCPG());
        String fieldName = obj.getName(getCPG());
        Field field = Hierarchy.findField(className, fieldName);

        if (field != null) {
            // If the field is final, we'll assume that the String value
            // is static.
            if (field.isFinal()) {
                pushValue(staticStringTypeInstance);
            } else {
                pushValue(type);
            }

            return;
        }
    } catch (ClassNotFoundException ex) {
        lookupFailureCallback.reportMissingClass(ex);
    }

    pushValue(type);
}
 
Example #29
Source File: ConfusedInheritance.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visitField(Field obj) {
    if (obj.isProtected()) {
        bugReporter.reportBug(new BugInstance(this, "CI_CONFUSED_INHERITANCE", LOW_PRIORITY).addClass(cls).addField(
                new FieldAnnotation(cls.getClassName(), obj.getName(), obj.getSignature(), obj.isStatic())));
    }
}
 
Example #30
Source File: CheckImmutableAnnotation.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Field obj) {
    if (!obj.isFinal() && !obj.isTransient() && !obj.isVolatile()) {
        bugReporter.reportBug(new BugInstance(this, "JCIP_FIELD_ISNT_FINAL_IN_IMMUTABLE_CLASS", NORMAL_PRIORITY).addClass(
                this).addVisitedField(this));
    }
}