Java Code Examples for org.apache.bcel.classfile.Method#getName()
The following examples show how to use
org.apache.bcel.classfile.Method#getName() .
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: GeneratingAnnotatedClassesTestCase.java From commons-bcel with Apache License 2.0 | 6 votes |
private void assertParameterAnnotations(final Method method, final int... expectedNumberOfParmeterAnnotations) { final String methodName= "For "+method.getName(); final ParameterAnnotationEntry[] parameterAnnotations= method.getParameterAnnotationEntries(); assertEquals(methodName, expectedNumberOfParmeterAnnotations.length, parameterAnnotations.length); int i= 0; for (final ParameterAnnotationEntry parameterAnnotation : parameterAnnotations) { final AnnotationEntry[] annos= parameterAnnotation.getAnnotationEntries(); final int expectedLength = expectedNumberOfParmeterAnnotations[i++]; assertEquals(methodName+" parameter "+i, expectedLength, annos.length); if(expectedLength!=0) { assertSimpleElementValue(annos[0]); } } }
Example 2
Source File: BadlyOverriddenAdapter.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
@Override public void visit(Method obj) { if (isAdapter) { String methodName = obj.getName(); String signature = methodMap.get(methodName); if (!Const.CONSTRUCTOR_NAME.equals(methodName) && signature != null) { if (!signature.equals(obj.getSignature())) { if (!badOverrideMap.keySet().contains(methodName)) { badOverrideMap.put(methodName, new BugInstance(this, "BOA_BADLY_OVERRIDDEN_ADAPTER", NORMAL_PRIORITY) .addClassAndMethod(this).addSourceLine(this)); } } else { badOverrideMap.put(methodName, null); } } } }
Example 3
Source File: UncallableMethodOfAnonymousClass.java From spotbugs with GNU Lesser General Public License v2.1 | 6 votes |
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 4
Source File: GeneratingAnnotatedClassesTestCase.java From commons-bcel with Apache License 2.0 | 5 votes |
private void assertMethodAnnotations(final Method method, final int expectedNumberAnnotations, final int nExpectedArrayValues) { final String methodName= method.getName(); final AnnotationEntry[] annos= method.getAnnotationEntries(); assertEquals("For "+methodName, expectedNumberAnnotations, annos.length); if(expectedNumberAnnotations!=0) { assertArrayElementValue(nExpectedArrayValues, annos[0]); } }
Example 5
Source File: TypeAnalysis.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
/** * Constructor. * * @param method * TODO * @param methodGen * the MethodGen whose CFG we'll be analyzing * @param cfg * the control flow graph * @param dfs * DepthFirstSearch of the method * @param typeMerger * object to merge types * @param visitor * a TypeFrameModelingVisitor to use to model the effect of * instructions * @param lookupFailureCallback * lookup failure callback * @param exceptionSetFactory * factory for creating ExceptionSet objects */ public TypeAnalysis(Method method, MethodGen methodGen, CFG cfg, DepthFirstSearch dfs, TypeMerger typeMerger, TypeFrameModelingVisitor visitor, RepositoryLookupFailureCallback lookupFailureCallback, ExceptionSetFactory exceptionSetFactory) { super(dfs); this.method = method; Code code = method.getCode(); if (code == null) { throw new IllegalArgumentException(method.getName() + " has no code"); } for (Attribute a : code.getAttributes()) { if (a instanceof LocalVariableTypeTable) { visitor.setLocalTypeTable((LocalVariableTypeTable) a); } } this.methodGen = methodGen; this.cfg = cfg; this.typeMerger = typeMerger; this.visitor = visitor; this.thrownExceptionSetMap = new HashMap<>(); this.lookupFailureCallback = lookupFailureCallback; this.exceptionSetFactory = exceptionSetFactory; this.instanceOfCheckMap = new HashMap<>(); if (DEBUG) { System.out.println("\n\nAnalyzing " + methodGen); } }
Example 6
Source File: OpcodeStackScanner.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
public static OpcodeStack getStackAt(JavaClass theClass, Method method, int pc) { Scanner scanner = new Scanner(theClass, method, pc); try { scanner.execute(); } catch (EarlyExitException e) { return e.stack; } throw new UnreachableCodeException(theClass.getClassName(), method.getName(), method.getSignature(), pc); }
Example 7
Source File: GenerateStubDialog.java From j-j-jvm with Apache License 2.0 | 5 votes |
protected Method[] getMethods(final ClassItem classItem, final boolean staticMethods) { final Set<Method> methodSet = new TreeSet<Method>(new Comparator<Method>() { @Override public int compare(final Method o1, final Method o2) { String s_name = o1.getName(); String s_name2 = o2.getName(); if (s_name.equals(s_name2)) { return 1; } return o1.getName().compareTo(o2.getName()); } }); final Method[] methods = classItem.getJavaClass().getMethods(); for (final Method method : methods) { if (method.isPrivate()) { continue; } if (staticMethods) { if (method.isStatic()) { methodSet.add(method); } } else { if (!method.isStatic()) { methodSet.add(method); } } } return methodSet.toArray(new Method[methodSet.size()]); }
Example 8
Source File: UnusedMethodCheck.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** @see AbstractReferenceCheck */ public boolean ignore(String aClassName, Method aMethod) { final String methodName = aMethod.getName(); return (super.ignore(aClassName, aMethod) || methodName.equals("<init>") || methodName.equals("<clinit>")); }
Example 9
Source File: HiddenStaticMethodCheck.java From contribution with GNU Lesser General Public License v2.1 | 5 votes |
/** @see AbstractReferenceCheck */ public boolean ignore(String aClassName, Method aMethod) { final String methodName = aMethod.getName(); return (/*super.ignore(aClassName, aMethod) || */methodName.equals("<init>") || methodName.equals("<clinit>") || methodName.equals("class$") || aMethod.toString().indexOf("[Synthetic]") > -1); }
Example 10
Source File: UselessSubclassMethod.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
private Method findSuperclassMethod(@DottedClassName String superclassName, Method subclassMethod) throws ClassNotFoundException { String methodName = subclassMethod.getName(); Type[] subArgs = null; JavaClass superClass = Repository.lookupClass(superclassName); Method[] methods = superClass.getMethods(); outer: for (Method m : methods) { if (m.getName().equals(methodName)) { if (subArgs == null) { subArgs = Type.getArgumentTypes(subclassMethod.getSignature()); } Type[] superArgs = Type.getArgumentTypes(m.getSignature()); if (subArgs.length == superArgs.length) { for (int j = 0; j < subArgs.length; j++) { if (!superArgs[j].equals(subArgs[j])) { continue outer; } } return m; } } } if (!"Object".equals(superclassName)) { @DottedClassName String superSuperClassName = superClass.getSuperclassName(); if (superSuperClassName.equals(superclassName)) { throw new ClassNotFoundException("superclass of " + superclassName + " is itself"); } return findSuperclassMethod(superSuperClassName, subclassMethod); } return null; }
Example 11
Source File: UselessSubclassMethod.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
@Override public void visitMethod(Method obj) { if ((interfaceMethods != null) && ((obj.getAccessFlags() & Const.ACC_ABSTRACT) != 0)) { String curDetail = obj.getName() + obj.getSignature(); for (String infMethodDetail : interfaceMethods) { if (curDetail.equals(infMethodDetail)) { bugReporter.reportBug(new BugInstance(this, "USM_USELESS_ABSTRACT_METHOD", LOW_PRIORITY).addClassAndMethod( getClassContext().getJavaClass(), obj)); } } } super.visitMethod(obj); }
Example 12
Source File: SelfCalls.java From spotbugs with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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 13
Source File: Pass2Verifier.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * 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 14
Source File: MethodGenFactory.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
@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 15
Source File: InnerClassAccessMap.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
/** * Return a map of inner-class member access method names to the fields that * they access for given class name. * * @param className * the name of the class * @return map of access method names to the fields they access */ private Map<String, InnerClassAccess> getAccessMapForClass(String className) throws ClassNotFoundException { Map<String, InnerClassAccess> map = classToAccessMap.get(className); if (map == null) { map = new HashMap<>(3); if (!className.startsWith("[")) { JavaClass javaClass = Repository.lookupClass(className); Method[] methodList = javaClass.getMethods(); for (Method method : methodList) { String methodName = method.getName(); if (!methodName.startsWith("access$")) { continue; } Code code = method.getCode(); if (code == null) { continue; } if (DEBUG) { System.out.println("Analyzing " + className + "." + method.getName() + " as an inner-class access method..."); } byte[] instructionList = code.getCode(); String methodSig = method.getSignature(); InstructionCallback callback = new InstructionCallback(javaClass, methodName, methodSig, instructionList); // try { new BytecodeScanner().scan(instructionList, callback); // } catch (LookupFailure lf) { // throw lf.getException(); // } InnerClassAccess access = callback.getAccess(); if (DEBUG) { System.out.println((access != null ? "IS" : "IS NOT") + " an inner-class access method"); } if (access != null) { map.put(methodName, access); } } } if (map.size() == 0) { map = Collections.emptyMap(); } else { map = new HashMap<>(map); } classToAccessMap.put(className, map); } return map; }
Example 16
Source File: GeneratingAnnotatedClassesTestCase.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Transform simple class from an immutable to a mutable object. The class * is annotated with an annotation that uses an array of SimpleAnnotations. */ public void testTransformClassToClassGen_ArrayAndAnnotationTypes() throws ClassNotFoundException { final JavaClass jc = getTestClass(PACKAGE_BASE_NAME+".data.AnnotatedWithCombinedAnnotation"); final ClassGen cgen = new ClassGen(jc); // Check annotations are correctly preserved final AnnotationEntryGen[] annotations = cgen.getAnnotationEntries(); assertTrue("Expected one annotation but found " + annotations.length, annotations.length == 1); final AnnotationEntryGen a = annotations[0]; assertTrue("That annotation should only have one value but has " + a.getValues().size(), a.getValues().size() == 1); final ElementValuePairGen nvp = a.getValues().get(0); final ElementValueGen value = nvp.getValue(); assertTrue("Value should be ArrayElementValueGen but is " + value, value instanceof ArrayElementValueGen); final ArrayElementValueGen arrayValue = (ArrayElementValueGen) value; assertTrue("Array value should be size one but is " + arrayValue.getElementValuesSize(), arrayValue .getElementValuesSize() == 1); final ElementValueGen innerValue = arrayValue.getElementValues().get(0); assertTrue( "Value in the array should be AnnotationElementValueGen but is " + innerValue, innerValue instanceof AnnotationElementValueGen); final AnnotationElementValueGen innerAnnotationValue = (AnnotationElementValueGen) innerValue; assertTrue("Should be called L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation; but is called: " + innerAnnotationValue.getAnnotation().getTypeName(), innerAnnotationValue.getAnnotation().getTypeSignature().equals( "L"+PACKAGE_BASE_SIG+"/data/SimpleAnnotation;")); // check the three methods final Method[] methods = cgen.getMethods(); assertEquals(3, methods.length); for (final Method method : methods) { final String methodName= method.getName(); if(methodName.equals("<init>")) { assertMethodAnnotations(method, 0, 1); assertParameterAnnotations(method, 0, 1); } else if(methodName.equals("methodWithArrayOfZeroAnnotations")) { assertMethodAnnotations(method, 1, 0); } else if(methodName.equals("methodWithArrayOfTwoAnnotations")) { assertMethodAnnotations(method, 1, 2); } else { fail("unexpected method "+method.getName()); } } }
Example 17
Source File: LinkageChecker.java From cloud-opensource-java with Apache License 2.0 | 4 votes |
/** * Returns the linkage errors for unimplemented methods in {@code classFile}. Such unimplemented * methods manifest as {@link AbstractMethodError} in runtime. */ private ImmutableList<SymbolProblem> findInterfaceProblems( ClassFile classFile, InterfaceSymbol interfaceSymbol) { String interfaceName = interfaceSymbol.getClassBinaryName(); if (classDumper.isSystemClass(interfaceName)) { return ImmutableList.of(); } ImmutableList.Builder<SymbolProblem> builder = ImmutableList.builder(); try { JavaClass implementingClass = classDumper.loadJavaClass(classFile.getBinaryName()); if (implementingClass.isAbstract()) { // Abstract class does not need to implement methods in an interface. return ImmutableList.of(); } JavaClass interfaceDefinition = classDumper.loadJavaClass(interfaceName); for (Method interfaceMethod : interfaceDefinition.getMethods()) { if (interfaceMethod.getCode() != null) { // This interface method has default implementation. Subclass does not have to implement // it. continue; } String interfaceMethodName = interfaceMethod.getName(); String interfaceMethodDescriptor = interfaceMethod.getSignature(); boolean methodFound = false; Iterable<JavaClass> typesToCheck = Iterables.concat(getClassHierarchy(implementingClass)); for (JavaClass javaClass : typesToCheck) { for (Method method : javaClass.getMethods()) { if (method.getName().equals(interfaceMethodName) && method.getSignature().equals(interfaceMethodDescriptor)) { methodFound = true; break; } } } if (!methodFound) { MethodSymbol missingMethodOnClass = new MethodSymbol( classFile.getBinaryName(), interfaceMethodName, interfaceMethodDescriptor, false); builder.add( new SymbolProblem(missingMethodOnClass, ErrorType.ABSTRACT_METHOD, classFile)); } } } catch (ClassNotFoundException ex) { // Missing classes are reported by findSymbolProblem method. } return builder.build(); }
Example 18
Source File: helloify.java From commons-bcel with Apache License 2.0 | 4 votes |
/** * Patch a method. */ private static Method helloifyMethod(Method m) { final Code code = m.getCode(); final int flags = m.getAccessFlags(); final String name = m.getName(); // Sanity check if (m.isNative() || m.isAbstract() || (code == null)) { return m; } // Create instruction list to be inserted at method start. final String mesg = "Hello from " + Utility.methodSignatureToString(m.getSignature(), name, Utility.accessToString(flags)); final InstructionList patch = new InstructionList(); patch.append(new GETSTATIC(out)); patch.append(new PUSH(cp, mesg)); patch.append(new INVOKEVIRTUAL(println)); final MethodGen mg = new MethodGen(m, class_name, cp); final InstructionList il = mg.getInstructionList(); final InstructionHandle[] ihs = il.getInstructionHandles(); if (name.equals("<init>")) { // First let the super or other constructor be called for (int j = 1; j < ihs.length; j++) { if (ihs[j].getInstruction() instanceof INVOKESPECIAL) { il.append(ihs[j], patch); // Should check: method name == "<init>" break; } } } else { il.insert(ihs[0], patch); } // Stack size must be at least 2, since the println method takes 2 argument. if (code.getMaxStack() < 2) { mg.setMaxStack(2); } m = mg.getMethod(); il.dispose(); // Reuse instruction handles return m; }
Example 19
Source File: GenerateStubDialog.java From j-j-jvm with Apache License 2.0 | 4 votes |
protected String makeMethodName(final String className, final Method method) { return className + '.' + method.getName() + '.' + method.getSignature(); }
Example 20
Source File: ClassParserUsingBCEL.java From spotbugs with GNU Lesser General Public License v2.1 | 2 votes |
/** * @param obj * the method to parse * @return a descriptor for the method */ protected MethodDescriptor parseMethod(Method obj) { return new MethodDescriptor(slashedClassName, obj.getName(), obj.getSignature(), obj.isStatic()); }