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

The following examples show how to use org.apache.bcel.classfile.Method#isStatic() . 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: 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 visitINVOKESTATIC(final INVOKESTATIC o) {
    try {
    // INVOKESTATIC is a LoadClass; the Class where the referenced method is declared in,
    // is therefore resolved/verified.
    // INVOKESTATIC is an InvokeInstruction, the argument and return types are resolved/verified,
    // too. So are the allowed method names.
    final String classname = o.getClassName(constantPoolGen);
    final JavaClass jc = Repository.lookupClass(classname);
    final Method m = getMethodRecursive(jc, o);
    if (m == null) {
        constraintViolated(o, "Referenced method '"+o.getMethodName(constantPoolGen)+"' with expected signature '"+
            o.getSignature(constantPoolGen) +"' not found in class '"+jc.getClassName()+"'.");
    } else if (! (m.isStatic())) { // implies it's not abstract, verified in pass 2.
        constraintViolated(o, "Referenced method '"+o.getMethodName(constantPoolGen)+"' has ACC_STATIC unset.");
    }

    } catch (final ClassNotFoundException e) {
    // FIXME: maybe not the best way to handle this
    throw new AssertionViolatedException("Missing class: " + e, e);
    }
}
 
Example 3
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 4
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 5
Source File: DumbMethods.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Method method) {
    String cName = getDottedClassName();

    for (SubDetector subDetector : subDetectors) {
        subDetector.initMethod(method);
    }

    // System.out.println(getFullyQualifiedMethodName());
    isPublicStaticVoidMain = method.isPublic() && method.isStatic() && "main".equals(getMethodName())
            || cName.toLowerCase().indexOf("benchmark") >= 0;
    prevOpcodeWasReadLine = false;
    Code code = method.getCode();
    if (code != null) {
        this.exceptionTable = code.getExceptionTable();
    }
    if (this.exceptionTable == null) {
        this.exceptionTable = new CodeException[0];
    }
    primitiveObjCtorSeen = null;
    ctorSeen = false;
    randomNextIntState = 0;
    checkForBitIorofSignedByte = false;
    sinceBufferedInputStreamReady = 100000;
    sawCheckForNonNegativeSignedByte = -1000;
    sawLoadOfMinValue = false;
    previousMethodCall = null;

}
 
Example 6
Source File: GenerateStubDialog.java    From j-j-jvm with Apache License 2.0 5 votes vote down vote up
protected String method2str(final Method method) {
  String modifier = "";

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

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

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

  modifier += method.getReturnType().toString();

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

  final StringBuilder buffer = new StringBuilder();
  org.apache.bcel.generic.Type[] argTypes = method.getArgumentTypes();

  for (int li = 0; li < argTypes.length; li++) {
    if (li > 0) {
      buffer.append(", ");
    }
    buffer.append(argTypes[li].toString());
  }

  modifier += '(' + buffer.toString() + ')';

  return modifier;
}
 
Example 7
Source File: PublicSemaphores.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Code obj) {
    Method m = getMethod();
    if (m.isStatic() || alreadyReported) {
        return;
    }

    state = SEEN_NOTHING;
    super.visit(obj);
}
 
Example 8
Source File: JavaClassAndMethod.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param method
 *            an XMethod specifying a specific method in a specific class
 * @throws ClassNotFoundException
 */
public JavaClassAndMethod(XMethod method) throws ClassNotFoundException {

    this.javaClass = Repository.lookupClass(method.getClassName());
    for (Method m : javaClass.getMethods()) {
        if (m.getName().equals(method.getName()) && m.getSignature().equals(method.getSignature())
                && m.isStatic() == method.isStatic()) {
            this.method = m;
            return;
        }
    }
    throw new IllegalArgumentException("Can't find " + method);
}
 
Example 9
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static @CheckForNull XMethod definedIn(JavaClass clazz, XMethod m) {
    for (Method m2 : clazz.getMethods()) {
        if (m.getName().equals(m2.getName()) && m.getSignature().equals(m2.getSignature()) && m.isStatic() == m2.isStatic()) {
            return XFactory.createXMethod(clazz, m2);
        }
    }
    return null;
}
 
Example 10
Source File: AnnotationDatabase.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
private boolean classDefinesMethod(JavaClass c, XMethod m) {
    for (Method definedMethod : c.getMethods()) {
        if (definedMethod.getName().equals(m.getName()) && definedMethod.getSignature().equals(m.getSignature())
                && definedMethod.isStatic() == m.isStatic()) {
            return true;
        }
    }
    return false;
}
 
Example 11
Source File: InvalidJUnitTest.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Method obj) {
    if (getMethodName().equals("suite") && !obj.isStatic()) {
        bugReporter.reportBug(new BugInstance(this, "IJU_SUITE_NOT_STATIC", NORMAL_PRIORITY).addClassAndMethod(this));
    }

    if (getMethodName().equals("suite") && obj.getSignature().startsWith("()") && obj.isStatic()) {
        if ((!obj.getSignature().equals("()Ljunit/framework/Test;") && !obj.getSignature().equals(
                "()Ljunit/framework/TestSuite;"))
                || !obj.isPublic()) {
            bugReporter.reportBug(new BugInstance(this, "IJU_BAD_SUITE_METHOD", NORMAL_PRIORITY).addClassAndMethod(this));
        }

    }
}
 
Example 12
Source File: FindMaskedFields.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public void visit(Method obj) {
    super.visit(obj);
    numParms = getNumberMethodArguments();
    if (!obj.isStatic()) {
        numParms++;
    }
    // System.out.println(obj);
    // System.out.println(numParms);
    staticMethod = obj.isStatic();
}
 
Example 13
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 14
Source File: FindNoSideEffectMethods.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method method) {
    constructor = method.getName().equals(Const.CONSTRUCTOR_NAME);
    classInit = method.getName().equals(Const.STATIC_INITIALIZER_NAME);
    calledMethods = new ArrayList<>();
    status = SideEffectStatus.NO_SIDE_EFFECT;
    if (hasNoSideEffect(getMethodDescriptor())) {
        handleStatus();
        return;
    }
    if (isObjectOnlyMethod(getMethodDescriptor())) {
        status = SideEffectStatus.OBJECT_ONLY;
    }
    if (method.isNative() || changedArg(getMethodDescriptor()) != -1) {
        status = SideEffectStatus.SIDE_EFFECT;
        handleStatus();
        return;
    }
    boolean sawImplementation = false;
    if (classInit) {
        superClinitCall();
    }
    if (!method.isStatic() && !method.isPrivate() && !method.isFinal() && !constructor && subtypes != null) {
        for (ClassDescriptor subtype : subtypes) {
            try {
                XClass xClass = Global.getAnalysisCache().getClassAnalysis(XClass.class, subtype);
                XMethod matchingMethod = xClass.findMatchingMethod(getMethodDescriptor());
                if (matchingMethod != null) {
                    sawImplementation = true;
                    sawCall(new MethodCall(matchingMethod.getMethodDescriptor(), TARGET_THIS), false);
                }
            } catch (CheckedAnalysisException e) {
            }
        }
    }
    if (method.isAbstract() || method.isInterface()) {
        if (!sawImplementation
                || getClassName().endsWith("Visitor") || getClassName().endsWith("Listener")
                || getClassName().startsWith("java/sql/")
                || (getClassName().equals("java/util/concurrent/Future") && !method.getName().startsWith("is"))
                || (getClassName().equals("java/lang/Process") && method.getName().equals("exitValue"))) {
            status = SideEffectStatus.SIDE_EFFECT;
        } else if (isObjectOnlyMethod(getMethodDescriptor())) {
            status = SideEffectStatus.OBJECT_ONLY;
        } else {
            String[] thrownExceptions = getXMethod().getThrownExceptions();
            if (thrownExceptions != null && thrownExceptions.length > 0) {
                status = SideEffectStatus.SIDE_EFFECT;
            }
        }
    }
    if ((status == SideEffectStatus.SIDE_EFFECT || status == SideEffectStatus.OBJECT_ONLY) || method.isAbstract()
            || method.isInterface() || method.isNative()) {
        handleStatus();
    }
}
 
Example 15
Source File: InheritanceUnsafeGetResource.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {
    methodIsStatic = obj.isStatic();
    state = 0;
    sawGetClass = -100;
}
 
Example 16
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 17
Source File: Naming.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {
    String mName = getMethodName();
    if (mName.length() == 1) {
        return;
    }
    if ("isRequestedSessionIdFromURL".equals(mName) || "isRequestedSessionIdFromUrl".equals(mName)) {
        return;
    }
    String sig = getMethodSig();
    if (mName.equals(baseClassName) && "()V".equals(sig)) {
        Code code = obj.getCode();
        Method realVoidConstructor = findVoidConstructor(getThisClass());
        if (code != null && !markedAsNotUsable(obj)) {
            int priority = NORMAL_PRIORITY;
            if (codeDoesSomething(code)) {
                priority--;
            } else if (!obj.isPublic() && getThisClass().isPublic()) {
                priority--;
            }
            boolean instanceMembers = false;
            for (Method m : this.getThisClass().getMethods()) {
                if (!m.isStatic() && m != obj && !isVoidConstructor(getThisClass(), m)) {
                    instanceMembers = true;
                }
            }
            for (Field f : this.getThisClass().getFields()) {
                if (!f.isStatic()) {
                    instanceMembers = true;
                }
            }
            if (!codeDoesSomething(code) && !instanceMembers && "java/lang/Object".equals(getSuperclassName())) {
                priority += 2;
            }
            if (hasBadMethodNames) {
                priority++;
            }
            if (!getXClass().getAnnotations().isEmpty()) {
                priority++;
            }
            if (realVoidConstructor != null) {
                priority = LOW_PRIORITY;
            }

            bugReporter.reportBug(new BugInstance(this, "NM_METHOD_CONSTRUCTOR_CONFUSION", priority).addClassAndMethod(this)
                    .lowerPriorityIfDeprecated());
            return;
        }
    } else if (badMethodName(mName)) {
        bugReporter.reportBug(new BugInstance(this, "NM_METHOD_NAMING_CONVENTION", classIsPublicOrProtected
                && (obj.isPublic() || obj.isProtected()) && !hasBadMethodNames ? NORMAL_PRIORITY : LOW_PRIORITY)
                        .addClassAndMethod(this));
    }

    if (obj.isAbstract()) {
        return;
    }
    if (obj.isPrivate()) {
        return;
    }

    if ("equal".equals(mName) && "(Ljava/lang/Object;)Z".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_BAD_EQUAL", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("hashcode".equals(mName) && "()I".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_HASHCODE", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }
    if ("tostring".equals(mName) && "()Ljava/lang/String;".equals(sig)) {
        bugReporter.reportBug(new BugInstance(this, "NM_LCASE_TOSTRING", HIGH_PRIORITY).addClassAndMethod(this)
                .lowerPriorityIfDeprecated());
        return;
    }

    if (obj.isPrivate() || obj.isStatic() || Const.CONSTRUCTOR_NAME.equals(mName)) {
        return;
    }

    String sig2 = removePackageNamesFromSignature(sig);
    String allSmall = mName.toLowerCase() + sig2;

    XMethod xm = getXMethod();
    {
        TreeSet<XMethod> s = canonicalToXMethod.computeIfAbsent(allSmall, k -> new TreeSet<>());
        s.add(xm);
    }

}
 
Example 18
Source File: SerializableIdiom.java    From spotbugs with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void visit(Method obj) {

    int accessFlags = obj.getAccessFlags();
    boolean isSynchronized = (accessFlags & Const.ACC_SYNCHRONIZED) != 0;
    if (Const.CONSTRUCTOR_NAME.equals(getMethodName()) && "()V".equals(getMethodSig()) && (accessFlags & Const.ACC_PUBLIC) != 0) {
        hasPublicVoidConstructor = true;
    }
    if (!Const.CONSTRUCTOR_NAME.equals(getMethodName()) && isSynthetic(obj)) {
        foundSynthetic = true;
        // System.out.println(methodName + isSynchronized);
    }

    if ("readExternal".equals(getMethodName()) && "(Ljava/io/ObjectInput;)V".equals(getMethodSig())) {
        sawReadExternal = true;
        if (DEBUG && !obj.isPrivate()) {
            System.out.println("Non-private readExternal method in: " + getDottedClassName());
        }
    } else if ("writeExternal".equals(getMethodName()) && "(Ljava/io/Objectoutput;)V".equals(getMethodSig())) {
        sawWriteExternal = true;
        if (DEBUG && !obj.isPrivate()) {
            System.out.println("Non-private writeExternal method in: " + getDottedClassName());
        }
    } else if ("readResolve".equals(getMethodName()) && getMethodSig().startsWith("()") && isSerializable) {
        sawReadResolve = true;
        if (!"()Ljava/lang/Object;".equals(getMethodSig())) {
            bugReporter.reportBug(new BugInstance(this, "SE_READ_RESOLVE_MUST_RETURN_OBJECT", HIGH_PRIORITY)
                    .addClassAndMethod(this));
        } else if (obj.isStatic()) {
            bugReporter.reportBug(new BugInstance(this, "SE_READ_RESOLVE_IS_STATIC", HIGH_PRIORITY).addClassAndMethod(this));
        } else if (obj.isPrivate()) {
            try {
                Set<ClassDescriptor> subtypes = AnalysisContext.currentAnalysisContext().getSubtypes2()
                        .getSubtypes(getClassDescriptor());
                if (subtypes.size() > 1) {
                    BugInstance bug = new BugInstance(this, "SE_PRIVATE_READ_RESOLVE_NOT_INHERITED", NORMAL_PRIORITY)
                            .addClassAndMethod(this);
                    boolean nasty = false;
                    for (ClassDescriptor subclass : subtypes) {
                        if (!subclass.equals(getClassDescriptor())) {

                            XClass xSub = AnalysisContext.currentXFactory().getXClass(subclass);
                            if (xSub != null && xSub.findMethod("readResolve", "()Ljava/lang/Object;", false) == null
                                    && xSub.findMethod("writeReplace", "()Ljava/lang/Object;", false) == null) {
                                bug.addClass(subclass).describe(ClassAnnotation.SUBCLASS_ROLE);
                                nasty = true;
                            }
                        }
                    }
                    if (nasty) {
                        bug.setPriority(HIGH_PRIORITY);
                    } else if (!getThisClass().isPublic()) {
                        bug.setPriority(LOW_PRIORITY);
                    }
                    bugReporter.reportBug(bug);
                }

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

    } else if ("readObject".equals(getMethodName()) && "(Ljava/io/ObjectInputStream;)V".equals(getMethodSig())
            && isSerializable) {
        sawReadObject = true;
        if (!obj.isPrivate()) {
            bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", isExternalizable ? NORMAL_PRIORITY : HIGH_PRIORITY)
                    .addClassAndMethod(this));
        }

    } else if ("readObjectNoData".equals(getMethodName()) && "()V".equals(getMethodSig()) && isSerializable) {

        if (!obj.isPrivate()) {
            bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", isExternalizable ? NORMAL_PRIORITY : HIGH_PRIORITY)
                    .addClassAndMethod(this));
        }

    } else if ("writeObject".equals(getMethodName()) && "(Ljava/io/ObjectOutputStream;)V".equals(getMethodSig())
            && isSerializable) {
        sawWriteObject = true;
        if (!obj.isPrivate()) {
            bugReporter.reportBug(new BugInstance(this, "SE_METHOD_MUST_BE_PRIVATE", isExternalizable ? NORMAL_PRIORITY : HIGH_PRIORITY)
                    .addClassAndMethod(this));
        }
    }

    if (isSynchronized) {
        if ("readObject".equals(getMethodName()) && "(Ljava/io/ObjectInputStream;)V".equals(getMethodSig()) && isSerializable) {
            bugReporter.reportBug(new BugInstance(this, "RS_READOBJECT_SYNC", isExternalizable ? LOW_PRIORITY : NORMAL_PRIORITY)
                    .addClassAndMethod(this));
        } else if ("writeObject".equals(getMethodName()) && "(Ljava/io/ObjectOutputStream;)V".equals(getMethodSig())
                && isSerializable) {
            writeObjectIsSynchronized = true;
        } else {
            foundSynchronizedMethods = true;
        }
    }
    super.visit(obj);

}
 
Example 19
Source File: MethodsGeneralPane.java    From ApkToolPlus with Apache License 2.0 4 votes vote down vote up
public void actionPerformed(ActionEvent event) {
	if (event.getSource() == addButton) {
		Method method = new Method();
		if (staticCB.isSelected()) {
			method.isStatic(true);
		}
		if (finalCB.isSelected()) {
			method.isFinal(true);
		}
		if (synchronizedCB.isSelected()) {
			method.isSynchronized(true);
		}
		if (nativeCB.isSelected()) {
			method.isNative(true);
		}
		if (abstractCB.isSelected()) {
			method.isAbstract(true);
		}
		if (strictCB.isSelected()) {
			method.isStrictfp(true);
		}
		int selectedItem = dropdown.getSelectedIndex();

		switch (selectedItem) {
		case 1:
			method.isPublic(true);
			break;
		case 2:
			method.isPrivate(true);
			break;
		case 3:
			method.isProtected(true);
			break;
		}

		String fileName = internalFrame.getFileName();
		int accessFlags = method.getAccessFlags();
		String methodName = name.getText();
		String methodDescriptor = descriptor.getText();
		ClassSaver classSaver = new ClassSaver(ClassSaver.ADD_METHOD, fileName,accessFlags, 
				methodName, methodDescriptor);
		ProgressDialog progressDialog = new ProgressDialog(
				internalFrame.getParentFrame(), null,
				"Adding method...");
		progressDialog.setRunnable(classSaver);
		progressDialog.setVisible(true);
		if (classSaver.exceptionOccured()) {
			ErrorReportWindow er = new ErrorReportWindow(internalFrame
					.getParentFrame(), classSaver.getExceptionVerbose(), "Adding method failed");

			er.pack();
			GUIHelper.centerOnParentWindow(er, internalFrame
					.getParentFrame());
			er.setVisible(true);
		} else {

			internalFrame.getParentFrame().doReload();
		}

	}

}
 
Example 20
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;
}