public int compare(Field a, Field b) {
      if (a == b) return 0;
      else if (a == null) return -1;
      else if (b == null) return 1;
      else if (a.equals(b)) return 0;

      int cmp = a.getName().compareTo(b.getName());
      if (cmp != 0) return cmp;

      cmp = a.getDeclaringClass().getName().compareTo(b.getDeclaringClass().getName());
      if (cmp != 0) return cmp;

      return a.getType().getName().compareTo(b.getType().getName());
    }
Ejemplo n.º 2
0
  public void printAll(Class c) {

    Constructor[] cs = this.getAllConstructorsFromClass(c);
    System.out.println("  Constructors:");
    for (Constructor constructor : cs) {
      System.out.print("    " + constructor);
      if (constructor.getDeclaringClass() != c)
        System.out.println(" (inherited from " + constructor.getDeclaringClass().getName() + ")");
      else System.out.println();
    }

    System.out.println("  Methods:");
    Method[] ms = this.getAllMethodsFromClass(c);
    for (Method method : ms) {
      System.out.print("    " + method);
      if (method.getDeclaringClass() != c)
        System.out.println(" (inherited from " + method.getDeclaringClass().getName() + ")");
      else System.out.println();
    }

    System.out.println("  Classes:");
    Class[] cls = this.getClassesFromClass(c);
    for (Class class1 : cls) {
      System.out.println("    " + class1);
    }

    System.out.println("  Fields:");
    Field[] fs = this.getFieldsFromClass(c);
    for (Field field : fs) {
      System.out.print("    " + field);
      if (field.getDeclaringClass() != c)
        System.out.println(" (inherited from " + field.getDeclaringClass().getName() + ")");
      else System.out.println();
    }

    System.out.println("  Interfaces:");
    Class[] is = this.getInterfacesFromClass(c);
    for (Class class2 : is) {
      System.out.println("    " + class2);
    }

    System.out.println("  Local Methods:");
    Method[] mls = this.getLocalMethodsFromClass(c);
    for (Method method2 : mls) {
      System.out.print("    " + method2);
      if (method2.getDeclaringClass() != c)
        System.out.println(" (inherited from " + method2.getDeclaringClass().getName() + ")");
      else System.out.println();
    }
  }
 /**
  * This method returns the maximum representation size of an object. <code>sizeSoFar</code> is the
  * object's size measured so far. <code>f</code> is the field being probed.
  *
  * <p>The returned offset will be the maximum of whatever was measured so far and <code>f</code>
  * field's offset and representation size (unaligned).
  */
 private static long adjustForField(long sizeSoFar, final Field f) {
   final Class<?> type = f.getType();
   final int fsize = type.isPrimitive() ? primitiveSizes.get(type) : NUM_BYTES_OBJECT_REF;
   if (objectFieldOffsetMethod != null) {
     try {
       final long offsetPlusSize =
           ((Number) objectFieldOffsetMethod.invoke(theUnsafe, f)).longValue() + fsize;
       return Math.max(sizeSoFar, offsetPlusSize);
     } catch (IllegalAccessException ex) {
       throw new RuntimeException("Access problem with sun.misc.Unsafe", ex);
     } catch (InvocationTargetException ite) {
       final Throwable cause = ite.getCause();
       if (cause instanceof RuntimeException) throw (RuntimeException) cause;
       if (cause instanceof Error) throw (Error) cause;
       // this should never happen (Unsafe does not declare
       // checked Exceptions for this method), but who knows?
       throw new RuntimeException(
           "Call to Unsafe's objectFieldOffset() throwed "
               + "checked Exception when accessing field "
               + f.getDeclaringClass().getName()
               + "#"
               + f.getName(),
           cause);
     }
   } else {
     // TODO: No alignments based on field type/ subclass fields alignments?
     return sizeSoFar + fsize;
   }
 }
Ejemplo n.º 4
0
 private ArrayList<Element> serializeFields(
     Field[] fields, Object object, Document doc) // serializes the fields
     {
   Class currentClass = object.getClass();
   ArrayList<Element> elements = new ArrayList<Element>();
   for (Field f : fields) {
     try {
       if (!f.getType().isPrimitive()) // Field not primitive, is a reference to another object
       {
       } else // field is primitive
       {
         Element newField = new Element("field");
         newField.setAttribute("name", f.getName());
         newField.setAttribute("declaringclass", f.getDeclaringClass().getName());
         Element newValue = new Element("value");
         newValue.addContent(f.get(object).toString());
         newField.addContent(newValue);
         elements.add(newField);
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   return elements;
 }
Ejemplo n.º 5
0
  protected void generateView(Map<String, org.ektorp.support.DesignDocument.View> views, Field f) {
    DocumentReferences referenceMetaData = f.getAnnotation(DocumentReferences.class);
    if (referenceMetaData == null) {
      LOG.warn("No DocumentReferences annotation found in field: ", f.getName());
      return;
    }

    if (referenceMetaData.view().length() > 0) {
      LOG.debug("Skipping view generation for field {} as view is already specified", f.getName());
      return;
    }

    if (Set.class.isAssignableFrom(f.getType())) {
      generateSetBasedDocRefView(views, f, referenceMetaData);
    } else {
      throw new ViewGenerationException(
          String.format(
              "The type of the field: %s in %s annotated with DocumentReferences is not supported. (Must be assignable from java.util.Set)",
              f.getName(), f.getDeclaringClass()));
    }
  }
Ejemplo n.º 6
0
 @Nonnull
 Class<?> getDeclaringTestClass() {
   return testedField.getDeclaringClass();
 }
Ejemplo n.º 7
0
  private void reflect(Scriptable scope, boolean includeProtected) {
    // We reflect methods first, because we want overloaded field/method
    // names to be allocated to the NativeJavaMethod before the field
    // gets in the way.

    Method[] methods = discoverAccessibleMethods(cl, includeProtected, includePrivate);
    for (int i = 0; i < methods.length; i++) {
      Method method = methods[i];
      int mods = method.getModifiers();
      boolean isStatic = Modifier.isStatic(mods);
      Map<String, Object> ht = isStatic ? staticMembers : members;
      String name = method.getName();
      Object value = ht.get(name);
      if (value == null) {
        ht.put(name, method);
      } else {
        ObjArray overloadedMethods;
        if (value instanceof ObjArray) {
          overloadedMethods = (ObjArray) value;
        } else {
          if (!(value instanceof Method)) Kit.codeBug();
          // value should be instance of Method as at this stage
          // staticMembers and members can only contain methods
          overloadedMethods = new ObjArray();
          overloadedMethods.add(value);
          ht.put(name, overloadedMethods);
        }
        overloadedMethods.add(method);
      }
    }

    // replace Method instances by wrapped NativeJavaMethod objects
    // first in staticMembers and then in members
    for (int tableCursor = 0; tableCursor != 2; ++tableCursor) {
      boolean isStatic = (tableCursor == 0);
      Map<String, Object> ht = isStatic ? staticMembers : members;
      for (String name : ht.keySet()) {
        MemberBox[] methodBoxes;
        Object value = ht.get(name);
        if (value instanceof Method) {
          methodBoxes = new MemberBox[1];
          methodBoxes[0] = new MemberBox((Method) value);
        } else {
          ObjArray overloadedMethods = (ObjArray) value;
          int N = overloadedMethods.size();
          if (N < 2) Kit.codeBug();
          methodBoxes = new MemberBox[N];
          for (int i = 0; i != N; ++i) {
            Method method = (Method) overloadedMethods.get(i);
            methodBoxes[i] = new MemberBox(method);
          }
        }
        NativeJavaMethod fun = new NativeJavaMethod(methodBoxes);
        if (scope != null) {
          ScriptRuntime.setFunctionProtoAndParent(fun, scope);
        }
        ht.put(name, fun);
      }
    }

    // Reflect fields.
    Field[] fields = getAccessibleFields();
    for (int i = 0; i < fields.length; i++) {
      Field field = fields[i];
      String name = field.getName();
      int mods = field.getModifiers();
      if (!includePrivate && !Modifier.isPublic(mods)) {
        continue;
      }
      try {
        boolean isStatic = Modifier.isStatic(mods);
        Map<String, Object> ht = isStatic ? staticMembers : members;
        Object member = ht.get(name);
        if (member == null) {
          ht.put(name, field);
        } else if (member instanceof NativeJavaMethod) {
          NativeJavaMethod method = (NativeJavaMethod) member;
          FieldAndMethods fam = new FieldAndMethods(scope, method.methods, field);
          Map<String, FieldAndMethods> fmht = isStatic ? staticFieldAndMethods : fieldAndMethods;
          if (fmht == null) {
            fmht = new HashMap<String, FieldAndMethods>();
            if (isStatic) {
              staticFieldAndMethods = fmht;
            } else {
              fieldAndMethods = fmht;
            }
          }
          fmht.put(name, fam);
          ht.put(name, fam);
        } else if (member instanceof Field) {
          Field oldField = (Field) member;
          // If this newly reflected field shadows an inherited field,
          // then replace it. Otherwise, since access to the field
          // would be ambiguous from Java, no field should be
          // reflected.
          // For now, the first field found wins, unless another field
          // explicitly shadows it.
          if (oldField.getDeclaringClass().isAssignableFrom(field.getDeclaringClass())) {
            ht.put(name, field);
          }
        } else {
          // "unknown member type"
          Kit.codeBug();
        }
      } catch (SecurityException e) {
        // skip this field
        Context.reportWarning(
            "Could not access field "
                + name
                + " of class "
                + cl.getName()
                + " due to lack of privileges.");
      }
    }

    // Create bean properties from corresponding get/set methods first for
    // static members and then for instance members
    for (int tableCursor = 0; tableCursor != 2; ++tableCursor) {
      boolean isStatic = (tableCursor == 0);
      Map<String, Object> ht = isStatic ? staticMembers : members;

      Map<String, BeanProperty> toAdd = new HashMap<String, BeanProperty>();

      // Now, For each member, make "bean" properties.
      for (String name : ht.keySet()) {
        // Is this a getter?
        boolean memberIsGetMethod = name.startsWith("get");
        boolean memberIsSetMethod = name.startsWith("set");
        boolean memberIsIsMethod = name.startsWith("is");
        if (memberIsGetMethod || memberIsIsMethod || memberIsSetMethod) {
          // Double check name component.
          String nameComponent = name.substring(memberIsIsMethod ? 2 : 3);
          if (nameComponent.length() == 0) continue;

          // Make the bean property name.
          String beanPropertyName = nameComponent;
          char ch0 = nameComponent.charAt(0);
          if (Character.isUpperCase(ch0)) {
            if (nameComponent.length() == 1) {
              beanPropertyName = nameComponent.toLowerCase();
            } else {
              char ch1 = nameComponent.charAt(1);
              if (!Character.isUpperCase(ch1)) {
                beanPropertyName = Character.toLowerCase(ch0) + nameComponent.substring(1);
              }
            }
          }

          // If we already have a member by this name, don't do this
          // property.
          if (ht.containsKey(beanPropertyName) || toAdd.containsKey(beanPropertyName)) {
            continue;
          }

          // Find the getter method, or if there is none, the is-
          // method.
          MemberBox getter = null;
          getter = findGetter(isStatic, ht, "get", nameComponent);
          // If there was no valid getter, check for an is- method.
          if (getter == null) {
            getter = findGetter(isStatic, ht, "is", nameComponent);
          }

          // setter
          MemberBox setter = null;
          NativeJavaMethod setters = null;
          String setterName = "set".concat(nameComponent);

          if (ht.containsKey(setterName)) {
            // Is this value a method?
            Object member = ht.get(setterName);
            if (member instanceof NativeJavaMethod) {
              NativeJavaMethod njmSet = (NativeJavaMethod) member;
              if (getter != null) {
                // We have a getter. Now, do we have a matching
                // setter?
                Class<?> type = getter.method().getReturnType();
                setter = extractSetMethod(type, njmSet.methods, isStatic);
              } else {
                // No getter, find any set method
                setter = extractSetMethod(njmSet.methods, isStatic);
              }
              if (njmSet.methods.length > 1) {
                setters = njmSet;
              }
            }
          }
          // Make the property.
          BeanProperty bp = new BeanProperty(getter, setter, setters);
          toAdd.put(beanPropertyName, bp);
        }
      }

      // Add the new bean properties.
      for (String key : toAdd.keySet()) {
        Object value = toAdd.get(key);
        ht.put(key, value);
      }
    }

    // Reflect constructors
    Constructor<?>[] constructors = getAccessibleConstructors();
    ctors = new MemberBox[constructors.length];
    for (int i = 0; i != constructors.length; ++i) {
      ctors[i] = new MemberBox(constructors[i]);
    }
  }