Ejemplo n.º 1
0
  private void validateClass(Class<?> source, ValidationProblemCollector problems) {
    int modifiers = source.getModifiers();

    if (Modifier.isInterface(modifiers)) {
      problems.add("Must be a class, not an interface");
    }

    if (source.getEnclosingClass() != null) {
      if (Modifier.isStatic(modifiers)) {
        if (Modifier.isPrivate(modifiers)) {
          problems.add("Class cannot be private");
        }
      } else {
        problems.add("Enclosed classes must be static and non private");
      }
    }

    Constructor<?>[] constructors = source.getDeclaredConstructors();
    for (Constructor<?> constructor : constructors) {
      if (constructor.getParameterTypes().length > 0) {
        problems.add("Cannot declare a constructor that takes arguments");
        break;
      }
    }

    Field[] fields = source.getDeclaredFields();
    for (Field field : fields) {
      int fieldModifiers = field.getModifiers();
      if (!field.isSynthetic()
          && !(Modifier.isStatic(fieldModifiers) && Modifier.isFinal(fieldModifiers))) {
        problems.add(field, "Fields must be static final.");
      }
    }
  }
Ejemplo n.º 2
0
  /** Discovers interesting (that we care about) things about the class. */
  protected void discover() {
    for (Class<? extends Annotation> c : interestingAnnotations) {
      addAnnotation(c);
    }

    List<Class<?>> lifecycleClasses = new ArrayList<Class<?>>();
    lifecycleClasses.add(clazz);

    EntityListeners entityLisAnn = (EntityListeners) getAnnotation(EntityListeners.class);
    if (entityLisAnn != null && entityLisAnn.value() != null && entityLisAnn.value().length != 0)
      for (Class<?> c : entityLisAnn.value()) lifecycleClasses.add(c);

    for (Class<?> cls : lifecycleClasses) {
      for (Method m : ReflectionUtils.getDeclaredAndInheritedMethods(cls)) {
        for (Class<? extends Annotation> c : lifecycleAnnotations) {
          if (m.isAnnotationPresent(c)) {
            addLifecycleEventMethod(c, m, cls.equals(clazz) ? null : cls);
          }
        }
      }
    }

    update();

    for (Field field : ReflectionUtils.getDeclaredAndInheritedFields(clazz, true)) {
      field.setAccessible(true);
      int fieldMods = field.getModifiers();
      if (field.isAnnotationPresent(Transient.class)) continue;
      else if (field.isSynthetic() && (fieldMods & Modifier.TRANSIENT) == Modifier.TRANSIENT)
        continue;
      else if (mapr.getOptions().actLikeSerializer
          && ((fieldMods & Modifier.TRANSIENT) == Modifier.TRANSIENT)) continue;
      else if (mapr.getOptions().ignoreFinals && ((fieldMods & Modifier.FINAL) == Modifier.FINAL))
        continue;
      else if (field.isAnnotationPresent(Id.class)) {
        MappedField mf = new MappedField(field, clazz);
        persistenceFields.add(mf);
        update();
      } else if (field.isAnnotationPresent(Property.class)
          || field.isAnnotationPresent(Reference.class)
          || field.isAnnotationPresent(Embedded.class)
          || field.isAnnotationPresent(Serialized.class)
          || isSupportedType(field.getType())
          || ReflectionUtils.implementsInterface(field.getType(), Serializable.class)) {
        persistenceFields.add(new MappedField(field, clazz));
      } else {
        if (mapr.getOptions().defaultMapper != null)
          persistenceFields.add(new MappedField(field, clazz));
        else if (log.isWarningEnabled())
          log.warning(
              "Ignoring (will not persist) field: "
                  + clazz.getName()
                  + "."
                  + field.getName()
                  + " [type:"
                  + field.getType().getName()
                  + "]");
      }
    }
  }
Ejemplo n.º 3
0
  public static void main(String... args) {
    try {
      Class<?> c = Class.forName(args[0]);
      int searchMods = 0x0;
      for (int i = 1; i < args.length; i++) {
        searchMods |= modifierFromString(args[i]);
      }

      Field[] flds = c.getDeclaredFields();
      out.format(
          "Fields in Class '%s' containing modifiers:  %s%n",
          c.getName(), Modifier.toString(searchMods));
      boolean found = false;
      for (Field f : flds) {
        int foundMods = f.getModifiers();
        // Require all of the requested modifiers to be present
        if ((foundMods & searchMods) == searchMods) {
          out.format(
              "%-8s [ synthetic=%-5b enum_constant=%-5b ]%n",
              f.getName(), f.isSynthetic(), f.isEnumConstant());
          found = true;
        }
      }

      if (!found) {
        out.format("No matching fields%n");
      }

      // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
      x.printStackTrace();
    }
  }
Ejemplo n.º 4
0
  /**
   * @param clazz the class for which to return all fields
   * @return all fields declared by the passed class and its superclasses
   */
  public static Collection<Field> getAllFields(Class<?> clazz) {
    // Note: use a linked hash map to keep the same order as the one used to declare the fields.
    Map<String, Field> fields = new LinkedHashMap<String, Field>();
    Class<?> targetClass = clazz;
    while (targetClass != null) {
      Field[] targetClassFields;
      try {
        targetClassFields = targetClass.getDeclaredFields();
      } catch (NoClassDefFoundError e) {
        // Provide a better exception message to more easily debug component loading issue.
        // Specifically with this error message we'll known which component failed to be
        // initialized.
        throw new NoClassDefFoundError(
            "Failed to get fields for class ["
                + targetClass.getName()
                + "] because the class ["
                + e.getMessage()
                + "] couldn't be found in the ClassLoader.");
      }

      for (Field field : targetClassFields) {
        // Make sure that if the same field is declared in a class and its superclass
        // only the field used in the class will be returned. Note that we need to do
        // this check since the Field object doesn't implement the equals method using
        // the field name.
        if (!field.isSynthetic() && !fields.containsKey(field.getName())) {
          fields.put(field.getName(), field);
        }
      }
      targetClass = targetClass.getSuperclass();
    }
    return fields.values();
  }
Ejemplo n.º 5
0
  private ObjectMap<String, FieldMetadata> cacheFields(Class type) {
    ArrayList<Field> allFields = new ArrayList();
    Class nextClass = type;
    while (nextClass != Object.class) {
      Collections.addAll(allFields, nextClass.getDeclaredFields());
      nextClass = nextClass.getSuperclass();
    }

    ObjectMap<String, FieldMetadata> nameToField = new ObjectMap();
    for (int i = 0, n = allFields.size(); i < n; i++) {
      Field field = allFields.get(i);

      int modifiers = field.getModifiers();
      if (Modifier.isTransient(modifiers)) continue;
      if (Modifier.isStatic(modifiers)) continue;
      if (field.isSynthetic()) continue;

      if (!field.isAccessible()) {
        try {
          field.setAccessible(true);
        } catch (AccessControlException ex) {
          continue;
        }
      }

      nameToField.put(field.getName(), new FieldMetadata(field));
    }
    typeToFields.put(type, nameToField);
    return nameToField;
  }
Ejemplo n.º 6
0
 private static boolean shouldSkip(Field field) {
   int modifiers = field.getModifiers();
   if ((modifiers & Modifier.TRANSIENT) == Modifier.TRANSIENT
       || (modifiers & Modifier.STATIC) == Modifier.STATIC
       || field.isSynthetic()
       || field.getType() == Class.class
       || field.getAnnotation(Ignore.class) != null) return true;
   return false;
 }
Ejemplo n.º 7
0
 /**
  * Constructs a Field Attributes object from the {@code f}.
  *
  * @param f the field to pull attributes from
  */
 FieldAttributes(final Class<?> parentClazz, final Field f) {
   Preconditions.checkNotNull(parentClazz);
   this.parentClazz = parentClazz;
   name = f.getName();
   declaredType = f.getType();
   isSynthetic = f.isSynthetic();
   modifiers = f.getModifiers();
   field = f;
 }
Ejemplo n.º 8
0
 private void createFields() {
   Class<?> cls = object.getClass();
   fields = cls.getDeclaredFields();
   List<Field> fieldList = new ArrayList<Field>();
   for (Field field : fields) {
     if (!field.isSynthetic()) {
       field.setAccessible(true);
       fieldList.add(field);
     }
   }
   fields = fieldList.toArray(new Field[fieldList.size()]);
 }
Ejemplo n.º 9
0
 private boolean _isIncludableField(Field f) {
   /* I'm pretty sure synthetic fields are to be skipped...
    * (methods definitely are)
    */
   if (f.isSynthetic()) {
     return false;
   }
   // Static fields are never included, nor transient
   int mods = f.getModifiers();
   if (Modifier.isStatic(mods) || Modifier.isTransient(mods)) {
     return false;
   }
   return true;
 }
Ejemplo n.º 10
0
 private void appendModel(Object o) throws IOException {
   w.write('{');
   boolean sep = false;
   for (Field field : o.getClass().getDeclaredFields()) {
     if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers())) {
       try {
         field.setAccessible(true);
         sep = append(field.getName(), field.get(o), sep) || sep;
       } catch (IllegalAccessException e) {
         // should never happen...
         throw new RuntimeException(e);
       }
     }
   }
   w.write('}');
 }
 private void checkString(T instance) {
   assertThat(
       instance.toString(),
       CoreMatchers.startsWith(
           type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{"));
   assertThat(instance.toString(), endsWith("}"));
   Class<?> currentType = type;
   do {
     for (Field field : type.getDeclaredFields()) {
       if (!field.isSynthetic()
           && !Modifier.isStatic(field.getModifiers())
           && !ignoredFields.contains(field.getName())) {
         assertThat(instance.toString(), containsString(field.getName()));
       }
     }
   } while ((currentType = currentType.getSuperclass()) != Object.class);
 }
  private List<java.lang.reflect.Field> getInheritedFields(Class<?> type) {
    List<java.lang.reflect.Field> result = new ArrayList<java.lang.reflect.Field>();

    Class<?> i = type;
    while (i != null && i != Object.class) {
      while (i != null && i != Object.class) {
        for (java.lang.reflect.Field field : i.getDeclaredFields()) {
          if (!field.isSynthetic()) {
            result.add(field);
          }
        }
        i = i.getSuperclass();
      }
    }

    return result;
  }
Ejemplo n.º 13
0
  public boolean excludeField(Field field, boolean serialize) {
    if ((modifiers & field.getModifiers()) != 0) {
      return true;
    }

    if (version != Excluder.IGNORE_VERSIONS
        && !isValidVersion(field.getAnnotation(Since.class), field.getAnnotation(Until.class))) {
      return true;
    }

    if (field.isSynthetic()) {
      return true;
    }

    if (requireExpose) {
      Expose annotation = field.getAnnotation(Expose.class);
      if (annotation == null || (serialize ? !annotation.serialize() : !annotation.deserialize())) {
        return true;
      }
    }

    if (!serializeInnerClasses && isInnerClass(field.getType())) {
      return true;
    }

    if (isAnonymousOrLocal(field.getType())) {
      return true;
    }

    List<ExclusionStrategy> list = serialize ? serializationStrategies : deserializationStrategies;
    if (!list.isEmpty()) {
      FieldAttributes fieldAttributes = new FieldAttributes(field);
      for (ExclusionStrategy exclusionStrategy : list) {
        if (exclusionStrategy.shouldSkipField(fieldAttributes)) {
          return true;
        }
      }
    }

    return false;
  }
Ejemplo n.º 14
0
 private static void linkChildren(RArray parentRealView, ViewTrace parentTrace) {
   Class viewClass = parentRealView.getClass();
   Field[] fields = getAllFields(viewClass);
   for (Field f : fields) {
     if (f.isSynthetic()) {
       continue;
     }
     Class fieldClass = f.getType();
     if (RArray.class.isAssignableFrom(fieldClass)) {
       try {
         f.setAccessible(true);
         Object o = f.get(parentRealView);
         if (o instanceof TracingView) {
           ((TracingView) o).getTrace().parentView = parentTrace;
         }
       } catch (IllegalAccessException e) {
         assert Utils.check(false, "can't read a view field " + e);
       }
     }
   }
 }
Ejemplo n.º 15
0
  public static Field[] getFields(Class<?> c, boolean includeStatic, boolean includeTransient) {
    String cacheKey = c.getCanonicalName() + ":" + includeStatic;
    Field[] array = fieldCache.get(cacheKey);

    if (array == null) {
      ArrayList<Field> fields = new ArrayList<Field>();

      List<Class<?>> classes = getClassHierarchy(c, false);

      // Reverse order so we make sure we maintain consistent order
      Collections.reverse(classes);

      for (Class<?> clazz : classes) {
        Field[] allFields = clazz.getDeclaredFields();
        for (Field f : allFields) {
          if ((!includeTransient)
              && ((f.getModifiers() & Modifier.TRANSIENT) == Modifier.TRANSIENT)) {
            continue;
          } else if (f.isSynthetic()) {
            // Synthetic fields are bad!!!
            continue;
          }
          boolean isStatic = (f.getModifiers() & Modifier.STATIC) == Modifier.STATIC;
          if ((isStatic) && (!includeStatic)) {
            continue;
          }
          if (f.getName().equalsIgnoreCase("serialVersionUID")) {
            continue;
          }
          f.setAccessible(true);
          fields.add(f);
        }
      }

      array = fields.toArray(new Field[fields.size()]);
      fieldCache.put(cacheKey, array);
    }
    return array;
  }
Ejemplo n.º 16
0
 TemplateVars() {
   if (getClass().getSuperclass() != TemplateVars.class) {
     throw new IllegalArgumentException("Class must extend TemplateVars directly");
   }
   ImmutableList.Builder<Field> fields = ImmutableList.builder();
   Field[] declaredFields = getClass().getDeclaredFields();
   for (Field field : declaredFields) {
     if (field.isSynthetic() || isStaticFinal(field)) {
       continue;
     }
     if (Modifier.isPrivate(field.getModifiers())) {
       throw new IllegalArgumentException("Field cannot be private: " + field);
     }
     if (Modifier.isStatic(field.getModifiers())) {
       throw new IllegalArgumentException("Field cannot be static unless also final: " + field);
     }
     if (field.getType().isPrimitive()) {
       throw new IllegalArgumentException("Field cannot be primitive: " + field);
     }
     fields.add(field);
   }
   this.fields = fields.build();
 }
 @Test
 public void testSynthetic() throws Exception {
   assertThat(describe(first).isSynthetic(), is(first.isSynthetic()));
   assertThat(describe(second).isSynthetic(), is(second.isSynthetic()));
 }
Ejemplo n.º 18
0
 @Override
 public boolean isSynthetic() {
   return field.isSynthetic();
 }
Ejemplo n.º 19
0
 /**
  * 检测非法:static final 或者 加了{@link Ignore} 注解
  *
  * @param f
  * @return
  */
 public static boolean isInvalid(Field f) {
   return (Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers()))
       || isIgnored(f)
       || f.isSynthetic();
 }
Ejemplo n.º 20
0
    private static void extractViewPattern(int depth, ViewTrace trace, StringBuilder p) {
      if (!processedViewsForPatterns.add(trace)) {
        p.append("(ALIASED) ");
      }

      p.append(trace.realView.getClass() + " size = " + trace.realView.size() + "\n");
      indent(depth, p);

      p.append("    use:");
      if (trace.materializeCount == 0 && trace.sumCount == 0 && trace.getCount == 0) {
        p.append(" UNUSED");
      } else {
        if (trace.getCount > 0) {
          p.append(" get");
        }
        if (trace.materializeCount > 0) {
          p.append(" materialize");
        }
        if (trace.sumCount > 0) {
          p.append(" sum");
        }
      }
      p.append("\n");

      if (false) {
        p.append("    allocationSite =");
        Site.printSite(trace.allocationSite, p);
        p.append("\n");
        indent(depth, p);
      }

      RArray view = trace.realView;
      Class viewClass = view.getClass();
      Field[] fields = getAllFields(viewClass);
      boolean printedField = false;

      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (RArray.class.isAssignableFrom(fieldClass)) {
          continue; // these later
        }
        indent(depth, p);
        p.append("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          p.append(o == null ? "null (" + fieldClass + ")" : o.getClass());
          p.append("\n");
          printedField = true;
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }

      boolean printNewline = printedField;
      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (!RArray.class.isAssignableFrom(fieldClass)) {
          continue;
        }
        if (printNewline) {
          p.append("\n");
          printNewline = false;
        }
        indent(depth, p);
        p.append("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          if (o instanceof TracingView) {
            p.append("VIEW ");
            TracingView child = (TracingView) o;
            extractViewPattern(depth + 2, child.getTrace(), p);
          } else {
            p.append("ARRAY " + o.getClass() + " size = " + ((RArray) o).size());
            if (o instanceof View) {
              ps.println("MISSED VIEW " + o);
            }
          }
          p.append("\n");
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }
    }
Ejemplo n.º 21
0
    private static void dumpView(int depth, ViewTrace trace) {
      printedIndividualViews.add(trace);

      ps.println(trace.realView + " size = " + trace.realView.size());
      if (TRACE_ALLOCATION_SITE) {
        indent(depth);
        ps.print("    allocationSite =");
        Site.printSite(trace.allocationSite);
        ps.println();
      }

      int unused = trace.unusedElements();
      int redundant = trace.redundantGets();

      boolean singleUse;
      Site[] useSites;

      if (TRACE_USE_SITES) {
        useSites = trace.useSites.toArray(new Site[trace.useSites.size()]);
        singleUse = (useSites.length == 1);
      } else if (TRACE_SINGLE_USE_SITE) {
        useSites = null;
        singleUse = !trace.multipleUseSites;
      } else {
        useSites = null;
        singleUse = false;
      }
      if (singleUse) {
        indent(depth);
        ps.print("    singleUseSite = US");
        Site.printSite(useSites != null ? useSites[0] : trace.singleUseSite);

        if (trace.getCount > 0) {
          ps.println(" (get)");
        } else if (trace.sumCount > 0) {
          ps.println(" (sum)");
        } else {
          ps.println(" (materialize)");
        }

      } else if (trace.getCount > 0) {
        if (TRACE_FIRST_GET_SITE) {
          indent(depth);
          ps.print("    firstGetSite =");
          Site.printSite(trace.firstGetSite);
          ps.println();
        }
        if (trace.materializeCount == 0 && trace.sumCount == 0) {
          if (unused > 0) {
            indent(depth);
            ps.println("    unusedElements = " + unused);
          }
          if (redundant > 0) {
            indent(depth);
            ps.println("    redundantGets = " + redundant + " (no materialize, sum)");
          }
        }
      } else {
        if (trace.materializeCount == 0 && trace.sumCount == 0) {
          indent(depth);
          ps.println("    UNUSED");
        } else {
          indent(depth);
          ps.println(
              "    materializeCount = "
                  + trace.materializeCount
                  + " sumCount = "
                  + trace.sumCount
                  + " getCount = "
                  + trace.getCount);
        }
      }
      if (TRACE_FIRST_MATERIALIZE_SITE && trace.materializeCount > 0 && !singleUse) {
        indent(depth);
        ps.print("    firstMaterializeSite =");
        Site.printSite(trace.firstMaterializeSite);
        ps.println();
      }
      if (TRACE_FIRST_SUM_SITE && trace.sumCount > 0 && !singleUse) {
        indent(depth);
        ps.print("    firstSumSite =");
        Site.printSite(trace.firstSumSite);
        ps.println();
      }
      if (TRACE_USE_SITES) {
        if (useSites.length != 1) {
          indent(depth);
          ps.println("    useSites (" + useSites.length + "):");
          for (Site s : useSites) {
            indent(depth);
            ps.print("        US");
            Site.printSite(s);
            ps.println();
          }
        }
      }

      ps.println();
      RArray view = trace.realView;
      Class viewClass = view.getClass();
      Field[] fields = getAllFields(viewClass);
      boolean printedField = false;

      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (RArray.class.isAssignableFrom(fieldClass)) {
          continue; // these later
        }
        indent(depth);
        ps.print("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          ps.println(f.get(view));
          printedField = true;
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }

      boolean printNewline = printedField;
      for (Field f : fields) {
        if (f.isSynthetic()) {
          continue;
        }
        Class fieldClass = f.getType();
        if (!RArray.class.isAssignableFrom(fieldClass)) {
          continue;
        }
        if (printNewline) {
          ps.println();
          printNewline = false;
        }
        indent(depth);
        ps.print("    " + f.getName() + " ");
        try {
          f.setAccessible(true);
          Object o = f.get(view);
          if (o instanceof TracingView) {
            ps.print("VIEW ");
            TracingView child = (TracingView) o;
            dumpView(depth + 2, child.getTrace());
          } else {
            ps.print("ARRAY " + o + " size = " + ((RArray) o).size());
            if (o instanceof View) {
              ps.println("MISSED VIEW " + o);
            }
          }
          ps.println();
        } catch (IllegalAccessException e) {
          assert Utils.check(false, "can't read a view field " + e);
        }
      }
    }