/** * Get the full description of a class by using reflection * * @param clazz * @return */ public static String getDescription(Class<?> clazz) { ClassType type = TypeOracle.Instance.getClassType(clazz); if (type == null) return clazz.getName() + ": Not Reflection Information available."; StringBuilder sb = new StringBuilder(); printAnnotations(type, sb); sb.append(type.getName()).append("\n"); sb.append("\n"); sb.append("Fields:").append("\n"); for (Field field : type.getFields()) { printAnnotations(field, sb); sb.append(field.getTypeName()).append(" ").append(field.getName()).append("\n"); } sb.append("\n"); if (type.findConstructor() != null) { sb.append("Constructor:").append("\n"); sb.append(type.findConstructor().toString()).append("\n"); } else { sb.append("No default Contructor\n"); } sb.append("\n"); sb.append("Methods:").append("\n"); for (Method method : type.getMethods()) { printAnnotations(method, sb); sb.append(method.toString()).append("\n"); } return sb.toString(); }
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute) { // DEBUG = // clazz.getName().equals("abc/Def") && // method.getName(clazz).equals("abc"); // TODO: Remove this when the code has stabilized. // Catch any unexpected exceptions from the actual visiting method. try { // Process the code. visitCodeAttribute0(clazz, method, codeAttribute); } catch (RuntimeException ex) { System.err.println("Unexpected error while computing stack sizes:"); System.err.println(" Class = [" + clazz.getName() + "]"); System.err.println( " Method = [" + method.getName(clazz) + method.getDescriptor(clazz) + "]"); System.err.println( " Exception = [" + ex.getClass().getName() + "] (" + ex.getMessage() + ")"); if (DEBUG) { method.accept(clazz, new ClassPrinter()); } throw ex; } }
private void commandMethods(StringTokenizer t) throws NoSessionException { if (!t.hasMoreTokens()) { env.error("No class specified."); return; } String idClass = t.nextToken(); ReferenceType cls = findClass(idClass); if (cls != null) { List<Method> methods = cls.allMethods(); OutputSink out = env.getOutputSink(); for (int i = 0; i < methods.size(); i++) { Method method = methods.get(i); out.print(method.declaringType().name() + " " + method.name() + "("); Iterator<String> it = method.argumentTypeNames().iterator(); if (it.hasNext()) { while (true) { out.print(it.next()); if (!it.hasNext()) { break; } out.print(", "); } } out.println(")"); } out.show(); } else { // ### Should validate class name syntax. env.failure("\"" + idClass + "\" is not a valid id or class name."); } }
@Override public Component getListCellRendererComponent( JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // ### We should indicate the current thread independently of the // ### selection, e.g., with an icon, because the user may change // ### the selection graphically without affecting the current // ### thread. super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value == null) { this.setText("<unavailable>"); } else { StackFrame frame = (StackFrame) value; Location loc = frame.location(); Method meth = loc.method(); String methName = meth.declaringType().name() + '.' + meth.name(); String position = ""; if (meth.isNative()) { position = " (native method)"; } else if (loc.lineNumber() != -1) { position = ":" + loc.lineNumber(); } else { long pc = loc.codeIndex(); if (pc != -1) { position = ", pc = " + pc; } } // Indices are presented to the user starting from 1, not 0. this.setText("[" + (index + 1) + "] " + methName + position); } return this; }
/** * Get value from annotation which named "methodName" i.e: Annotation(value="abc") * * @param annotation annotation * @param methodName "value" * @return "abc" */ public static Object getAnnotationValueByName(Annotation annotation, String methodName) { ClassType type = TypeOracle.Instance.getClassType(annotation.annotationType()); if (type == null) reflectionRequired(annotation.annotationType().getName(), ""); Method method = type.findMethod(methodName); return method.invoke(annotation); }
public void visitCodeAttribute0(Clazz clazz, Method method, CodeAttribute codeAttribute) { if (DEBUG) { System.out.println( "StackSizeComputer: " + clazz.getName() + "." + method.getName(clazz) + method.getDescriptor(clazz)); } // Try to reuse the previous array. int codeLength = codeAttribute.u4codeLength; if (evaluated.length < codeLength) { evaluated = new boolean[codeLength]; stackSizes = new int[codeLength]; } else { Arrays.fill(evaluated, 0, codeLength, false); } // The initial stack is always empty. stackSize = 0; maxStackSize = 0; // Evaluate the instruction block starting at the entry point of the method. evaluateInstructionBlock(clazz, method, codeAttribute, 0); // Evaluate the exception handlers. codeAttribute.exceptionsAccept(clazz, method, this); }
/** * Add a method to a resource. Follow references to methods across WADL file boundaries * * @param method the WADL method element to process * @param resource the resource * @param file the URI of the current WADL file being processed */ protected void addMethodToResource(ResourceNode resource, Method method, URI file) { String href = method.getHref(); if (href != null && href.length() > 0) { // dereference resource if (!href.startsWith("#")) { // referecnce to element in another document file = getReferencedFile(file, href); } method = dereferenceLocalHref(file, href, Method.class); } if (method != null) { MethodNode n = new MethodNode(method, resource); Request request = method.getRequest(); if (request != null) { for (Param p : request.getParam()) { n.getQueryParameters().add(p); } for (RepresentationType r : request.getRepresentation()) { addRepresentation(n.getSupportedInputs(), r, file); } } Response response = method.getResponse(); if (response != null) { for (JAXBElement<RepresentationType> o : response.getRepresentationOrFault()) { if (o.getName().getLocalPart().equals("representation")) { addRepresentation(n.getSupportedOutputs(), o.getValue(), file); } else if (o.getName().getLocalPart().equals("fault")) { FaultNode fn = new FaultNode(o.getValue()); n.getFaults().add(fn); } } } } }
void compareAllVariables(String className, String methodName) throws Exception { println("compareAllVariables for method: " + className + "." + methodName); Method method = getMethod(className, methodName); List localVars; try { localVars = method.variables(); println("\n Success: got a list of all method variables: " + methodName); } catch (com.sun.jdi.AbsentInformationException ex) { failure("\n AbsentInformationException has been thrown"); return; } // We consider N*N combinations for set of N variables int index1 = 0; for (Iterator it1 = localVars.iterator(); it1.hasNext(); index1++) { LocalVariable lv1 = (LocalVariable) it1.next(); int index2 = 0; for (Iterator it2 = localVars.iterator(); it2.hasNext(); index2++) { LocalVariable lv2 = (LocalVariable) it2.next(); println("\n Two variables:"); printVariable(lv1, index1); printVariable(lv2, index2); println(""); if (index1 == index2) { compareTwoEqualVars(lv1, lv2); } else { compareTwoDifferentVars(lv1, lv2); } } } println(""); return; }
/** * Find a string return value of a method context "function() { return 'foo'}" First match wins */ @Nullable public static String getMethodReturnAsString( @NotNull PhpClass phpClass, @NotNull String methodName) { Method method = phpClass.findMethodByName(methodName); if (method == null) { return null; } final Set<String> values = new HashSet<String>(); method.acceptChildren( new PsiRecursiveElementWalkingVisitor() { @Override public void visitElement(PsiElement element) { if (PhpElementsUtil.getMethodReturnPattern().accepts(element)) { String value = PhpElementsUtil.getStringValue(element); if (value != null && StringUtils.isNotBlank(value)) { values.add(value); } } super.visitElement(element); } }); if (values.size() == 0) { return null; } // we support only first item return values.iterator().next(); }
private String getShortClassName(String name, String method) { classAndMethod.className = name; classAndMethod.methodName = method; String out = methodAlias.get(classAndMethod); if (out != null) return out; StringBuilder sb = new StringBuilder(); int lastDot = name.lastIndexOf('.'); if (lastDot < 0) return name + '.' + method; int prevIndex = -1; for (; ; ) { char ch = name.charAt(prevIndex + 1); sb.append(ch); int idx = name.indexOf('.', prevIndex + 1); ch = name.charAt(idx + 1); if (idx >= lastDot || Character.isUpperCase(ch)) { sb.append(name.substring(idx)); break; } prevIndex = idx; } return sb.toString() + '.' + method; }
@Override public void run(Object thisPointer, CallFrame callingFrame) { System.out.println("Method " + self.getName() + " was called."); // setup call frame CallFrame callFrame = self.metaCreateCallFrame(); callFrame.setCallingFrame(callFrame); callFrame.setThis(thisPointer); if (self.getScope() == Scope.MEMBER && callFrame.getThis() == null) { throw new ModelException("Member variable without this pointer."); } for (Variable localVar : self.getVariable()) { callFrame.getLocalVariable().add(localVar.metaCreateSlot()); } // run body for (Statement statement : self.getBody()) { if (statement instanceof Assignment) { callFrame .slotForVariable(((Assignment) statement).getAssignTo()) .setValue(((Assignment) statement).getAssignWith().evaluate(callFrame)); } else if (statement instanceof MethodCall) { Method method = ((MethodCall) statement).getCalledMethod(); if (method.getScope() == Scope.MEMBER) { method.run(((MethodCall) statement).getTarget().evaluate(callFrame), callFrame); } } } // destroy call frame for (Slot slot : new ListImpl<Slot>((callFrame.getLocalVariable()))) { slot.metaDelete(); } callFrame.metaDelete(); }
public void visitCodeAttribute(Clazz clazz, Method method, CodeAttribute codeAttribute) { // DEBUG = // clazz.getName().equals("abc/Def") && // method.getName(clazz).equals("abc"); // The minimum variable size is determined by the arguments. codeAttribute.u2maxLocals = ClassUtil.internalMethodParameterSize(method.getDescriptor(clazz), method.getAccessFlags()); if (DEBUG) { System.out.println( "VariableSizeUpdater: " + clazz.getName() + "." + method.getName(clazz) + method.getDescriptor(clazz)); System.out.println(" Max locals: " + codeAttribute.u2maxLocals + " <- parameters"); } // Go over all instructions. codeAttribute.instructionsAccept(clazz, method, this); // Remove the unused variables of the attributes. codeAttribute.attributesAccept(clazz, method, variableCleaner); }
/** * @param name the name of the method * @param parameterTypes the types of the parameters of the method * @return the declared method that matches the name and parameter types of this type. * @throws NoSuchMethodException */ public Method getDeclaredMethod(String name, Class... parameterTypes) throws NoSuchMethodException { for (Method m : getDeclaredMethods()) { if (m.match(name, parameterTypes)) return m; } throw new NoSuchMethodException(); }
private void addCriteriaMethods(TopLevelClass topLevelClass, int newMethodsStart) { if (!generateCriteriaMethods) return; InnerClass criteria = null; for (InnerClass c : topLevelClass.getInnerClasses()) { if (c.getType().getShortName().equals("Criteria")) criteria = c; } if (criteria == null) return; boolean owner = false; for (Field f : criteria.getFields()) if (ExampleMethodsChainPlugin.OWNER.equals(f.getName())) owner = true; if (!owner) return; for (ListIterator<Method> methods = topLevelClass.getMethods().listIterator(newMethodsStart); methods.hasNext(); ) { Method base = methods.next(); if (base.getVisibility() != PUBLIC || base.isStatic() || base.isConstructor()) continue; Method m = method(PUBLIC, base.getReturnType(), base.getName()); StringBuilder sb = new StringBuilder(); sb.append("return ").append(ExampleMethodsChainPlugin.OWNER).append(".").append(base.getName()).append("("); for (ListIterator<Parameter> params = base.getParameters().listIterator(); params.hasNext(); ) { if (params.hasPrevious()) sb.append(", "); Parameter p = params.next(); m.addParameter(new Parameter(p.getType(), p.getName())); sb.append(p.getName()); } sb.append(");"); m.addBodyLine(sb.toString()); criteria.addMethod(m); } }
public static Imports allOf(@Nonnull final Method method) { Check.notNull(method, "method"); final List<Import> imports = Lists.newArrayList(); imports.add(Import.of(method.getReturnType().getType())); imports.addAll(ofAnnotations(method.getAnnotations()).asList()); return new Imports(imports); }
/** * Marks the hierarchy of implementing or overriding methods corresponding to the given method, if * any. */ protected void markMethodHierarchy(Clazz clazz, Method method) { int accessFlags = method.getAccessFlags(); if ((accessFlags & (ClassConstants.ACC_PRIVATE | ClassConstants.ACC_STATIC)) == 0 && !ClassUtil.isInitializer(method.getName(clazz))) { // We can skip private and static methods in the hierarchy, and // also abstract methods, unless they might widen a current // non-public access. int requiredUnsetAccessFlags = ClassConstants.ACC_PRIVATE | ClassConstants.ACC_STATIC | ((accessFlags & ClassConstants.ACC_PUBLIC) == 0 ? 0 : ClassConstants.ACC_ABSTRACT); clazz.accept( new ConcreteClassDownTraveler( new ClassHierarchyTraveler( true, true, false, true, new NamedMethodVisitor( method.getName(clazz), method.getDescriptor(clazz), new MemberAccessFilter(0, requiredUnsetAccessFlags, this))))); } }
static Method lookup(String method) { for (Method m : Method.values()) { if (m.toString().equalsIgnoreCase(method)) { return m; } } return null; }
/** * Get all methods which annotated by clazz * * @param classType * @param clazz * @return */ public static Method[] getAllMethods(ClassType classType, Class<? extends Annotation> clazz) { List<Method> methods = new ArrayList<Method>(); for (Method method : classType.getMethods()) { Annotation annotation = getAnnotation(method.getAnnotations(), clazz); if (annotation != null) methods.add(method); } return methods.toArray(new Method[0]); }
@Override public String render() { StringBuilder sb = new StringBuilder(); for (Method m : methods) { m.renderInto(sb); } return sb.toString(); }
public void methodsAccept(MemberVisitor memberVisitor) { for (int index = 0; index < methods.length; index++) { Method method = methods[index]; if (method != null) { method.accept(this, memberVisitor); } } }
/** @return method object with given name and signature, or null */ public Method containsMethod(String name, String signature) { for (Iterator e = method_vec.iterator(); e.hasNext(); ) { Method m = (Method) e.next(); if (m.getName().equals(name) && m.getSignature().equals(signature)) return m; } return null; }
@Nullable public static Method getClassMethod(PhpClass phpClass, String methodName) { for (Method method : phpClass.getMethods()) { if (method.getName().equals(methodName)) { return method; } } return null; }
/** @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); }
private Method createCRUDMethod( final String name, final Parameter crudParameter, final Return crudReturn) { final Method method = new Method(); method.setName(name); method.setReturn(crudReturn); method.getParameter().add(crudParameter); return method; }
/** * Creates a new Task using two strings, the Application name and Method name. * * @param a Application name. * @param m Method name * @return Task */ public static Task Create(final String a, final String m) { Application application = new Application(); application.setName(a); Method method = new Method(); method.setName(m); return Create(application, method); }
public boolean mayHaveImplementations(Method method) { return (u2accessFlags & ClassConstants.INTERNAL_ACC_FINAL) == 0 && (method == null || ((method.getAccessFlags() & (ClassConstants.INTERNAL_ACC_PRIVATE | ClassConstants.INTERNAL_ACC_STATIC | ClassConstants.INTERNAL_ACC_FINAL)) == 0 && !method.getName(this).equals(ClassConstants.INTERNAL_METHOD_NAME_INIT))); }
/** * Return method with given name * * @param name * @return */ public Method getMethod(String name) { for (Method m : methods) { if (m.getName().equals(name)) { return m; } } return null; }
/** * Interprets Plugin class data to verify whether it is compatible with an existing payment method * to use for payments and other various economic activity. * * @param plugin Plugin data from bukkit, Internal Class file. * @return Method <em>or</em> Null */ public static Method createMethod(Plugin plugin) { for (Method method : Methods) { if (method.isCompatible(plugin)) { method.setPlugin(plugin); return method; } } return null; }
private void dumpStack(ThreadReference thread, boolean showPC) { // ### Check for these. // env.failure("Thread no longer exists."); // env.failure("Target VM must be in interrupted state."); // env.failure("Current thread isn't suspended."); // ### Should handle extremely long stack traces sensibly for user. List<StackFrame> stack = null; try { stack = thread.frames(); } catch (IncompatibleThreadStateException e) { env.failure("Thread is not suspended."); } // ### Fix this! // ### Previously mishandled cases where thread was not current. // ### Now, prints all of the stack regardless of current frame. int frameIndex = 0; // int frameIndex = context.getCurrentFrameIndex(); if (stack == null) { env.failure("Thread is not running (no stack)."); } else { OutputSink out = env.getOutputSink(); int nFrames = stack.size(); for (int i = frameIndex; i < nFrames; i++) { StackFrame frame = stack.get(i); Location loc = frame.location(); Method meth = loc.method(); out.print(" [" + (i + 1) + "] "); out.print(meth.declaringType().name()); out.print('.'); out.print(meth.name()); out.print(" ("); if (meth.isNative()) { out.print("native method"); } else if (loc.lineNumber() != -1) { try { out.print(loc.sourceName()); } catch (AbsentInformationException e) { out.print("<unknown>"); } out.print(':'); out.print(loc.lineNumber()); } out.print(')'); if (showPC) { long pc = loc.codeIndex(); if (pc != -1) { out.print(", pc = " + pc); } } out.println(); } out.show(); } }
public static ArrayList<Method> getClassPublicMethod(PhpClass phpClass) { ArrayList<Method> methods = new ArrayList<Method>(); for (Method method : phpClass.getMethods()) { if (method.getAccess().isPublic() && !method.getName().startsWith("__")) { methods.add(method); } } return methods; }