Exemple #1
1
 private static void initFields(Class<?> clazz) {
   Field[] srcFields = clazz.getDeclaredFields();
   for (Field field : srcFields) {
     Log.d(TAG, "modify " + clazz.getName() + "." + field.getName() + " flag:");
     setFieldFlag(field);
   }
 }
Exemple #2
0
  /**
   * copy
   *
   * @param dest
   * @param orig
   * @param ignoreNull 忽略null,即orig为空的字段不做copy
   * @author Joeson
   */
  public static void copy(Object dest, Object orig, boolean ignoreNull) {
    if (null == dest || null == orig) {
      return;
    }

    Class destClz = dest.getClass();
    Class origClz = orig.getClass();

    Field[] destFields = destClz.getDeclaredFields();
    Field[] origFields = origClz.getDeclaredFields();

    for (Field origField : origFields) {
      try {
        String fieldName = origField.getName();
        origField.setAccessible(true);
        if (!ignoreNull || null != origField.get(orig)) {
          for (Field destField : destFields) {
            if (destField.getName().equals(origField.getName())
                && destField.getType().equals(origField.getType())) {
              destField.setAccessible(true);
              Object o = origField.get(orig);
              BeanUtils.copyProperty(dest, fieldName, o);
              break;
            }
          }
        }
      } catch (Exception e) {
        logger.error("copyNonNull exception.", e);
        throw new RuntimeException("copyNonNull exception.." + e.getMessage());
      }
    }
  }
  protected static boolean matchesSegment(Field field, String segmentTag) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      if (StringUtils.equals(segmentTag, es.tag())) {
        return true;
      }
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (StringUtils.isNotBlank(ediSegmentGroupTag)) {
        if (StringUtils.equals(segmentTag, ediSegmentGroupTag)) {
          return true;
        }
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return matchesSegment(clz.getDeclaredFields()[0], segmentTag);
        }
      }
    }

    return false;
  }
  protected static String getSegmentTag(Field field, boolean inner) {
    Class<?> clz = field.getType();

    if (Collection.class.isAssignableFrom(clz)) {
      clz = getCollectionType(field);
    }

    if (clz.isAnnotationPresent(EDISegment.class)) {
      EDISegment es = clz.getAnnotation(EDISegment.class);
      return es.tag();
    } else if (clz.isAnnotationPresent(EDISegmentGroup.class)) {
      EDISegmentGroup esg = clz.getAnnotation(EDISegmentGroup.class);

      String ediSegmentGroupTag = esg.header();

      if (!inner && StringUtils.isNotBlank(ediSegmentGroupTag)) {
        return ediSegmentGroupTag;
      } else {
        // get the segement group's first field, and recurse.
        if (clz.getDeclaredFields().length > 0) {
          return getSegmentTag(clz.getDeclaredFields()[0], false);
        }
      }
    }

    return null;
  }
  /**
   * Handles case-insensitive lookups Note: Tests for plural form of fieldName, e.g. when the field
   * is a collection
   *
   * @param objClass
   * @param fieldName
   * @return
   */
  public static Field findField(Class objClass, String fieldName) {

    LOG.debug("Looking for field " + fieldName + " in " + objClass.getName());
    Field result = null;

    Field[] fields = objClass.getDeclaredFields();
    for (Field f : fields) {

      if (f.getName().compareToIgnoreCase(fieldName) == 0) {

        result = f;
        break;
      }
    }

    // Handle collections
    if (result == null) {

      fields = objClass.getDeclaredFields();
      for (Field f : fields) {

        if (f.getName().compareToIgnoreCase(fieldName + "s") == 0) {

          result = f;
          break;
        }
      }
    }

    return result;
  }
  /**
   * This class returns a ClassStatsHolder object which holds statistics about a class
   *
   * @param classname
   * @return
   */
  private ClassStatsHolder getStatistics(String classname) {
    ClassStatsHolder ret = null;
    try {
      // get methods, constructors etc
      Class theClass = Class.forName(classname);
      Integer numFields = theClass.getDeclaredFields().length;
      Method[] methods = theClass.getDeclaredMethods();
      Integer members = (theClass.getDeclaredFields().length) + methods.length;
      Constructor[] constructors = theClass.getDeclaredConstructors();

      // create ararys of method names an number of parameters
      String[] totalMethods = new String[methods.length];
      Integer[] paramaters = new Integer[methods.length];
      for (int i = 0; i < methods.length; i++) {
        totalMethods[i] = methods[i].getName();
        paramaters[i] = methods[i].getParameterTypes().length;
      }

      ret =
          new ClassStatsHolder(
              classname, totalMethods, paramaters, members, constructors, numFields);
    } catch (ClassNotFoundException e) {
      e.printStackTrace(); // will never be reached if recursion is done
    }

    return ret;
  }
  /**
   * 创建一个对象实例 该实例的值由一对象的相同属性赋值
   *
   * @param className 要创建实例的类全名
   * @param object 用于赋值的对象
   * @return
   */
  public Object fill(Class clazz, Object object) {

    try {
      // 通过类名得到实例
      Class instanceClass = clazz;
      Object instance = instanceClass.newInstance();

      Class objectClass = object.getClass();

      // 分别得到两个类声明的属性
      Field[] instanceFields = instanceClass.getDeclaredFields();
      Field[] objectFields = objectClass.getDeclaredFields();

      // 得到两个对象相同的属性
      Field instanceField;
      Field objectField;
      int instanceLength = instanceFields.length;
      for (int i = 0; i < instanceLength; i++) {

        instanceField = instanceFields[i];

        int objectLength = objectFields.length;
        for (int j = 0; j < objectLength; j++) {

          objectField = objectFields[j];

          // 遇到相同的属性 就把赋值对象的值 赋予要创建的实例
          if (instanceField.getName().equals(objectField.getName())) {

            // 关掉安全检查 使得能访问到非公有属性
            instanceField.setAccessible(true);
            objectField.setAccessible(true);

            // 把赋值对象的值 赋予要创建的实例
            instanceField.set(instance, objectField.get(object));
          }
        }
      }

      return instance;

    } catch (InstantiationException e) {
      // TODO 自动生成 catch 块
      e.printStackTrace();
    } catch (IllegalAccessException e) {
      // TODO 自动生成 catch 块
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      // TODO 自动生成 catch 块
      e.printStackTrace();
    } catch (SecurityException e) {
      // TODO 自动生成 catch 块
      e.printStackTrace();
    }

    return null;
  }
Exemple #8
0
  public static String getPortTypeOfComponentsPort(
      Component comp, Port port /*, String inport_outport*/)
      throws SecurityException, IllegalArgumentException {
    Class<?> c = comp.getClass();
    // System.out.println("class: " + c.getName());
    Field[] fields = c.getDeclaredFields();
    ArrayList<Field> allFields = new ArrayList<>();
    for (Field f : fields) allFields.add(f);
    // add fields from superclasses (required in the case of multi-level inheriting classes, e.g.,
    // Merge8x1)
    Class<?> currSuperClass = c.getSuperclass();
    while (currSuperClass != null) {
      Field[] superfields = currSuperClass.getDeclaredFields();
      for (Field f : superfields) allFields.add(f);
      currSuperClass = currSuperClass.getSuperclass();
    }

    for (Field f : allFields) // (Field f : fields)
    {
      if (f.getType().getSimpleName().equals("InPort")
          || f.getType()
              .getSimpleName()
              .equals("OutPort")) { // f.getType().getSimpleName().equals(inport_outport)
        // System.out.println(f.getName() + ": " + f.getType());
        f.setAccessible(true);
        try {
          if (f.get(comp).equals(port)) {
            // System.out.println("generic type: " + f.getGenericType().getTypeName());
            String portType =
                f.getGenericType()
                    .getTypeName(); // ch.alari.sacre.OutPort<ch.alari.sacre.TextToken>
            // extract <...>
            int beg = portType.lastIndexOf('<');
            String tokenType = "java.lang.Object";
            if (beg
                != -1) // ch.alari.sacre.OutPort, may be defined as such. then
                       // tokenType="java.lang.Object"
            tokenType = portType.substring(beg + 1, portType.lastIndexOf('>'));
            return tokenType;
            //                        PortType anno = f.getAnnotation(PortType.class);
            //                        if(anno!=null)
            //                        {
            //                            System.out.println("anno: " + anno.value());
            //                            return anno.value();
            //                        }
            //                        else
            //                            return null;
          }
        } catch (IllegalAccessException iae) {
          iae.printStackTrace();
        }
      }
    }
    return null;
  }
 /** Gets all declared fields and all inherited fields. */
 protected Set<Field> getFields(Class<?> c) {
   Set<Field> fields = new HashSet<Field>(Arrays.asList(c.getDeclaredFields()));
   while ((c = c.getSuperclass()) != null) {
     for (Field f : c.getDeclaredFields()) {
       if (!Modifier.isStatic(f.getModifiers()) && !Modifier.isPrivate(f.getModifiers())) {
         fields.add(f);
       }
     }
   }
   return fields;
 }
  private static boolean testConvexPolygonArch() {
    boolean pass = true;
    int test = 1;
    int cnt;
    ConvexPolygon poly;
    Class cl;
    Class[] temp;

    System.out.println("ConvexPolygon architecture tests...");

    Point a = new Point(7, 7);
    Point b = new Point(0, 9);
    Point c = new Point(-3, -5);
    Point d = new Point(2, -6);
    Point e = new Point(12, 0);
    Point[] vertices = new Point[5];
    vertices[0] = new Point(a);
    vertices[1] = new Point(b);
    vertices[2] = new Point(c);
    vertices[3] = new Point(d);
    vertices[4] = new Point(e);

    poly = new ConvexPolygon(vertices, Color.cyan, false);

    cl = poly.getClass();

    pass &= test(cl.getConstructors().length == 1, test++);
    pass &= test((temp = cl.getInterfaces()).length == 1, test++);
    pass &= test(temp[0].getName().equals("Shape"), test++);
    pass &= test(verifyEqualsMethodSignature(cl), test++);

    cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC);
    pass &= test(cnt == 9, test++);

    cnt = cl.getFields().length;
    pass &= test(cnt == 0, test++);

    cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED);
    pass &= test(cnt == 0, test++);

    cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE);
    pass &= test(cnt == 3, test++);

    // Count and test number of of PACKAGE fields
    cnt =
        cl.getDeclaredFields().length
            - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE)
            - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED)
            - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC);
    pass &= test(cnt == 0, test++);

    return pass;
  }
 /**
  * An introspection based equality predicate for GenericObjects.
  *
  * @other the other object to test against.
  */
 public boolean equals(Object that) {
   if (!this.getClass().equals(that.getClass())) return false;
   Class myclass = this.getClass();
   Field[] fields = myclass.getDeclaredFields();
   Class hisclass = that.getClass();
   Field[] hisfields = hisclass.getDeclaredFields();
   for (int i = 0; i < fields.length; i++) {
     Field f = fields[i];
     Field g = hisfields[i];
     // Only print protected and public members.
     int modifier = f.getModifiers();
     if ((modifier & Modifier.PRIVATE) == Modifier.PRIVATE) continue;
     Class fieldType = f.getType();
     String fieldName = f.getName();
     if (fieldName.compareTo("stringRepresentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("indentation") == 0) {
       continue;
     }
     if (fieldName.compareTo("inputText") == 0) {
       continue;
     }
     try {
       // Primitive fields are printed with type: value
       if (fieldType.isPrimitive()) {
         String fname = fieldType.toString();
         if (fname.compareTo("int") == 0) {
           if (f.getInt(this) != g.getInt(that)) return false;
         } else if (fname.compareTo("short") == 0) {
           if (f.getShort(this) != g.getShort(that)) return false;
         } else if (fname.compareTo("char") == 0) {
           if (f.getChar(this) != g.getChar(that)) return false;
         } else if (fname.compareTo("long") == 0) {
           if (f.getLong(this) != g.getLong(that)) return false;
         } else if (fname.compareTo("boolean") == 0) {
           if (f.getBoolean(this) != g.getBoolean(that)) return false;
         } else if (fname.compareTo("double") == 0) {
           if (f.getDouble(this) != g.getDouble(that)) return false;
         } else if (fname.compareTo("float") == 0) {
           if (f.getFloat(this) != g.getFloat(that)) return false;
         }
       } else if (g.get(that) == f.get(this)) return true;
       else if (f.get(this) == null) return false;
       else if (g.get(that) == null) return false;
       else return f.get(this).equals(g.get(that));
     } catch (IllegalAccessException ex1) {
       InternalErrorHandler.handleException(ex1);
     }
   }
   return false;
 }
  public void setProperties(String[] properties) {
    this.properties = properties;

    for (Integer loc_Conta1 = 0; loc_Conta1 < properties.length; loc_Conta1++) {
      for (Integer loc_Conta = 0; loc_Conta < tipo.getDeclaredFields().length; loc_Conta++) {

        if (tipo.getDeclaredFields()[loc_Conta].getName().equals(properties[loc_Conta1])) {
          indexes.put(loc_Conta1, loc_Conta);
          break;
        }
      }
    }
  }
Exemple #13
0
 private List<Field> allFields(final Class<?> c) {
   List<Field> l = fieldsCache.get(c);
   if (l == null) {
     l = new LinkedList<Field>();
     final Field[] fields = c.getDeclaredFields();
     addAll(l, fields);
     Class<?> sc = c;
     while ((sc = sc.getSuperclass()) != Object.class && sc != null) {
       addAll(l, sc.getDeclaredFields());
     }
     fieldsCache.putIfAbsent(c, l);
   }
   return l;
 }
  private static Field getField(Class<?> clazz, String fieldName) {
    Field field = null;
    String key = clazz.getName() + "#" + fieldName;
    field = FIELD_CACHE.get(key);

    // find it if not cached
    if (field == null && !FIELD_CACHE.containsKey(key)) {
      Class<?> tmpClass = clazz;
      do {
        for (Field tmpField : tmpClass.getDeclaredFields()) {
          String candidateName = tmpField.getName();
          if (candidateName.equals(fieldName)) {
            // field.setAccessible(true);
            FIELD_CACHE.put(key, tmpField);
            field = tmpField;
            break;
          }
        }
        tmpClass = tmpClass.getSuperclass();
      } while (tmpClass != null && field == null);
    }
    if (field == null) {
      LOGGER.warn("Field '" + fieldName + "' not found on class " + clazz);
      // HashMap handles null values so we can use containsKey to cach
      // invalid fields and hence skip the reflection scan
      FIELD_CACHE.put(key, null);
    }
    return field;

    // throw new RuntimeException("Field '" + fieldName +
    // "' not found on class " + clazz);
  }
Exemple #15
0
  /** object 旧对象,copy 新对象,escapeField 忽略拷贝字段 相同结构对象值对应拷�? */
  public void copy2(Object object, Object copy, List<String> escapeField) throws Exception {
    if (object == null) {
      return;
    }
    Class<?> classType = object.getClass();

    // 获得对象的所有成员变�?

    Field[] fields =
        (Field[])
            ArrayUtils.addAll(
                classType.getSuperclass().getDeclaredFields(),
                classType.getDeclaredFields()); // .getDeclaredFields();
    for (Field field : fields) {
      String name = field.getName();
      if (!escapeField.contains(name)) {
        String firstLetter = name.substring(0, 1).toUpperCase(); // 将属性的首字母转换为大写
        String getMethodName = "get" + firstLetter + name.substring(1);
        String setMethodName = "set" + firstLetter + name.substring(1);

        Method getMethod = classType.getMethod(getMethodName, new Class[] {});
        Method setMethod = copy.getClass().getMethod(setMethodName, new Class[] {field.getType()});

        Object value =
            getMethod.invoke(
                object, new Object[] {}); // invoke()方法的第�?个参数是指调用Method的对�?,第二个参数是Method的参�? 详见API
        if (value != null) {
          setMethod.invoke(copy, new Object[] {value});
        }
      }
    }
  }
Exemple #16
0
 Field[] keyFields() {
   Class c = clazz;
   try {
     List<Field> fields = new ArrayList<Field>();
     while (!c.equals(Object.class)) {
       for (Field field : c.getDeclaredFields()) {
         // TODO: add cashe field->isAnnotationPresent
         if (InternalCache.isEnableAnnotationPresent()) {
           if (InternalCache.isAnnotationPresent(Id.class, field)
               || InternalCache.isAnnotationPresent(EmbeddedId.class, field)) {
             field.setAccessible(true);
             fields.add(field);
           }
         } else {
           if (field.isAnnotationPresent(Id.class)
               || field.isAnnotationPresent(EmbeddedId.class)) {
             field.setAccessible(true);
             fields.add(field);
           }
         }
       }
       c = c.getSuperclass();
     }
     final Field[] f = fields.toArray(new Field[fields.size()]);
     if (f.length == 0) {
       throw new UnexpectedException("Cannot get the object @Id for an object of type " + clazz);
     }
     return f;
   } catch (Exception e) {
     throw new UnexpectedException(
         "Error while determining the object @Id for an object of type " + clazz);
   }
 }
Exemple #17
0
 public List<Model.Property> listProperties() {
   List<Model.Property> properties = new ArrayList<Model.Property>();
   Set<Field> fields = new LinkedHashSet<Field>();
   Class<?> tclazz = clazz;
   while (!tclazz.equals(Object.class)) {
     Collections.addAll(fields, tclazz.getDeclaredFields());
     tclazz = tclazz.getSuperclass();
   }
   for (Field f : fields) {
     int mod = f.getModifiers();
     if (Modifier.isTransient(mod) || Modifier.isStatic(mod)) {
       continue;
     }
     if (f.isAnnotationPresent(Transient.class)) {
       continue;
     }
     if (f.isAnnotationPresent(NoBinding.class)) {
       NoBinding a = f.getAnnotation(NoBinding.class);
       List<String> values = Arrays.asList(a.value());
       if (values.contains("*")) {
         continue;
       }
     }
     Model.Property mp = buildProperty(f);
     if (mp != null) {
       properties.add(mp);
     }
   }
   return properties;
 }
Exemple #18
0
  void initIndexes(Class<A> indexClass) {
    Field[] fields = indexClass.getDeclaredFields();
    indexedFields = new ArrayList<Field>();

    for (Field f : fields) {
      Index<A, RK> index = null;
      SubstringIndex s = f.getAnnotation(SubstringIndex.class);
      ExactIndex e = f.getAnnotation(ExactIndex.class);
      PrefixIndex p = f.getAnnotation(PrefixIndex.class);
      String indexName = indexClass.getSimpleName() + "_" + f.getName();
      if (s != null) {
        index = new SubstringIndexImpl<A, RK>(this, indexName, s);
      }
      if (e != null) {
        index = new ExactIndexImpl<A, RK>(this, indexName, e);
      }
      if (p != null) {
        index = new PrefixIndexImpl<A, RK>(this, indexName, p);
      }
      if (index != null) {
        indexedFields.add(f);
        f.setAccessible(true);
        indices.put(f.getName(), index);
      }
    }
  }
Exemple #19
0
  public static OptionSchema newOptionSchema(Class<?> optionHolderType) {
    OptionSchema optionSchema = new OptionSchema();

    // traverses through super classes
    for (Class<?> optionHolderClass = optionHolderType;
        optionHolderClass != null;
        optionHolderClass = optionHolderClass.getSuperclass()) {
      // looks for bean methods annotated with Option or Argument
      for (Method eachMethod : optionHolderClass.getDeclaredMethods()) {
        if (eachMethod.getAnnotation(Option.class) != null) optionSchema.addOptionItem(eachMethod);

        if (eachMethod.getAnnotation(Argument.class) != null)
          optionSchema.addArgumentItem(eachMethod);
      }

      // looks for bean fields annotated with Option or Argument
      for (Field f : optionHolderClass.getDeclaredFields()) {
        if (f.getAnnotation(Option.class) != null) optionSchema.addOptionItem(f);

        if (f.getAnnotation(Argument.class) != null) optionSchema.addArgumentItem(f);
      }

      if (optionHolderClass.getAnnotation(Usage.class) != null) {
        optionSchema.setUsage(optionHolderClass);
      }
    }

    return optionSchema;
  }
  public JAXBContext getContext(Class<?> objectType) {
    if (types.contains(objectType)) {
      return context;
    }

    // need to see if class has any ArrayList types, if so, add those to arrays
    Field[] fields = objectType.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
      if (fields[i].getType().isAssignableFrom(ArrayList.class)) {
        String simpleName = fields[i].getName();
        simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
        arrays.add(simpleName);
      }
    }

    String simpleName = objectType.getSimpleName();
    simpleName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
    arrays.add(simpleName);
    types.add(objectType);
    try {
      JSONConfiguration config =
          JSONConfiguration.mapped()
              .rootUnwrapping(true)
              .arrays(arrays.toArray(new String[] {}))
              .build();
      context = new JSONJAXBContext(config, types.toArray(new Class[] {}));
      return getContext(objectType);
    } catch (JAXBException e) {
    }
    return null;
  }
Exemple #21
0
  /**
   * 反序列化简单对象
   *
   * @param jo json对象
   * @param clazz 实体类类型
   * @return 反序列化后的实例
   * @throws JSONException
   */
  public static <T> T parseObject(JSONObject jo, Class<T> clazz) throws JSONException {
    if (clazz == null || isNull(jo)) {
      return null;
    }

    T obj = newInstance(clazz);
    if (obj == null) {
      return null;
    }
    if (isMap(clazz)) {
      setField(obj, jo);
    } else {
      // 取出bean里的所有方法
      Method[] methods = clazz.getDeclaredMethods();
      Field[] fields = clazz.getDeclaredFields();
      for (Field f : fields) {
        String setMetodName = parseMethodName(f.getName(), "set");
        if (!haveMethod(methods, setMetodName)) {
          continue;
        }
        try {
          Method fieldMethod = clazz.getMethod(setMetodName, f.getType());
          setField(obj, fieldMethod, f, jo);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return obj;
  }
Exemple #22
0
 public List<SysUser> find(SysUser object)
     throws IllegalArgumentException, IllegalAccessException {
   List<SysUser> list = null;
   String hql = "from sys_user u where 1=1";
   int index = 0;
   List parameters = new ArrayList(); // 存放参数
   Class type = object.getClass();
   if (object != null) {
     Field[] declaredFields = type.getDeclaredFields();
     for (int i = 0; i < declaredFields.length; i++) {
       Field filed = declaredFields[i];
       filed.setAccessible(true);
       String column = filed.getName();
       Object parameter = null;
       parameter = filed.get(object);
       if (parameter != null && parameter.hashCode() != 0 && !column.equals("serialVersionUID")) {
         parameters.add(parameter);
         hql += " and u." + column + "=?";
         System.out.println(hql);
       }
     }
   }
   Object[] str = new Object[parameters.size()];
   for (Object ob : parameters) {
     str[index] = ob;
     index++;
   }
   list = (List<SysUser>) this.getHibernateTemplate().find(hql, str);
   return list;
 }
  public String toHTML(String template) {
    String templateText = "";
    File templateFile = new File(Consts.TEMPLATESPATH + "/" + template + ".tpl");
    try {
      templateText = new String(Files.readAllBytes(templateFile.toPath()), StandardCharsets.UTF_8);

      Class<?> c = this.getClass();
      Field[] fields = c.getDeclaredFields();

      // TODO:setSpec
      for (Field field : fields) {
        String replaceStr = StringEscapeUtils.escapeHtml(field.get(this).toString());
        templateText =
            templateText.replaceAll(
                "\\{\\$" + field.getName() + "\\}", Matcher.quoteReplacement(replaceStr));
      }
    } catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return templateText;
  }
 private static void reflectionAppend(
     Object obj,
     Object obj1,
     Class class1,
     CompareToBuilder comparetobuilder,
     boolean flag,
     String as[]) {
   Field afield[] = class1.getDeclaredFields();
   AccessibleObject.setAccessible(afield, true);
   int i = 0;
   do {
     if (i >= afield.length || comparetobuilder.comparison != 0) {
       return;
     }
     Field field = afield[i];
     if (!ArrayUtils.contains(as, field.getName())
         && field.getName().indexOf('$') == -1
         && (flag || !Modifier.isTransient(field.getModifiers()))
         && !Modifier.isStatic(field.getModifiers())) {
       try {
         comparetobuilder.append(field.get(obj), field.get(obj1));
       } catch (IllegalAccessException illegalaccessexception) {
         throw new InternalError("Unexpected IllegalAccessException");
       }
     }
     i++;
   } while (true);
 }
 public StringBuffer parseFields2JSON() {
   Class<?> clazz = this.getClass();
   Field[] fields = clazz.getDeclaredFields();
   StringBuffer buffer = new StringBuffer("{");
   for (Field f : fields) {
     try {
       buffer.append(f.getName()).append(":");
       Object value = f.get(this);
       if (value != null) {
         if (value instanceof String) {
           buffer.append("'").append(value).append("'").append(", ");
         } else {
           buffer.append(value).append(", ");
         }
       } else {
         buffer.append("''").append(", ");
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   int offset = buffer.length();
   buffer.replace(offset - 2, offset, "");
   return buffer.append("}");
 }
Exemple #26
0
 @SuppressWarnings("unchecked")
 protected static <T extends Bits<T>> T[] _values(Class<T> cls) {
   if (!Bits.class.isAssignableFrom(cls)) {
     throw new IllegalArgumentException(cls.getName() + " is not a subclass of " + Bits.class);
   }
   try {
     Set<T> values = new TreeSet<T>();
     for (Field field : cls.getDeclaredFields()) {
       int mod = field.getModifiers();
       if (Modifier.isPublic(mod)
           && Modifier.isStatic(mod)
           && Modifier.isFinal(mod)
           && field.getType() == cls) {
         T bits = (T) field.get(null);
         Bits<?> bits_ =
             bits; // Avoids "... has private access in Bits" error with javac from OpenJDK 1.7
         bits_.name = field.getName();
         if (bits_.mask != 0) {
           values.add(bits);
         }
       }
     }
     return (T[]) values.toArray((T[]) Array.newInstance(cls, values.size()));
   } catch (IllegalAccessException e) {
     throw new Error(e);
   }
 }
Exemple #27
0
  /**
   * Returns all config options for the given component.
   *
   * @param component
   * @return
   */
  public static Map<ConfigOption, Class<?>> getConfigOptionTypes(
      Class<?> component, boolean useSuperTypes) {
    Map<ConfigOption, Class<?>> optionTypes =
        new TreeMap<ConfigOption, Class<?>>(
            new Comparator<ConfigOption>() {

              @Override
              public int compare(ConfigOption o1, ConfigOption o2) {
                return o1.name().compareTo(o2.name());
              }
            });
    Field[] fields = component.getDeclaredFields();
    if (useSuperTypes) {
      if (useSuperTypes) {
        fields =
            ObjectArrays.concat(fields, component.getSuperclass().getDeclaredFields(), Field.class);
      }
    }
    for (Field f : fields) {
      ConfigOption option = f.getAnnotation(ConfigOption.class);
      if (option != null) {
        optionTypes.put(option, f.getType());
      }
    }
    return optionTypes;
  }
Exemple #28
0
 private void addFields(Class<?> clazz) {
   Field[] fields = clazz.getDeclaredFields();
   for (Field field : fields) {
     if (canAccessPrivateMethods()) {
       try {
         field.setAccessible(true);
       } catch (Exception e) {
         // Ignored. This is only a final precaution, nothing we can do.
       }
     }
     if (field.isAccessible()) {
       if (!setMethods.containsKey(field.getName())) {
         // issue #379 - removed the check for final because JDK 1.5 allows
         // modification of final fields through reflection (JSR-133). (JGB)
         // pr #16 - final static can only be set by the classloader
         int modifiers = field.getModifiers();
         if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) {
           addSetField(field);
         }
       }
       if (!getMethods.containsKey(field.getName())) {
         addGetField(field);
       }
     }
   }
   if (clazz.getSuperclass() != null) {
     addFields(clazz.getSuperclass());
   }
 }
  protected void retrieveClassModelStructure() {

    this.classHandleName = objectClassModel.getAnnotation(ObjectClass.class).name();

    fields = objectClassModel.getDeclaredFields();
    Map<Class, Coder> tmpMapCoder = new HashMap<Class, Coder>();
    Coder coderTmp = null;

    try {
      for (Field f : fields) {
        if (f.isAnnotationPresent(Attribute.class)) {
          coderTmp = tmpMapCoder.get(f.getAnnotation(Attribute.class).coder());
          if (coderTmp == null) {
            coderTmp = f.getAnnotation(Attribute.class).coder().newInstance();
            tmpMapCoder.put(f.getAnnotation(Attribute.class).coder(), coderTmp);
          }
          matchingObjectCoderIsValid(f, coderTmp);
          mapFieldCoder.put(f.getAnnotation(Attribute.class).name(), coderTmp);
        }
      }
    } catch (InstantiationException | IllegalAccessException e) {
      logger.error("Error in retreving the annotations of the fields");
      e.printStackTrace();
    } finally {
      tmpMapCoder = null;
      coderTmp = null;
    }
  }
Exemple #30
0
  /**
   * bean对象转Map
   *
   * @param obj 实例对象
   * @return map集合
   */
  public static Map<String, String> beanToMap(Object obj) {
    Class<?> cls = obj.getClass();
    Map<String, String> valueMap = new HashMap<String, String>();
    // 取出bean里的所有方法
    Method[] methods = cls.getDeclaredMethods();
    Field[] fields = cls.getDeclaredFields();
    for (Field field : fields) {
      try {
        String fieldType = field.getType().getSimpleName();
        String fieldGetName = parseMethodName(field.getName(), "get");
        if (!haveMethod(methods, fieldGetName)) {
          continue;
        }
        Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
        Object fieldVal = fieldGetMet.invoke(obj, new Object[] {});
        String result = null;
        if ("Date".equals(fieldType)) {
          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
          result = sdf.format((Date) fieldVal);

        } else {
          if (null != fieldVal) {
            result = String.valueOf(fieldVal);
          }
        }
        valueMap.put(field.getName(), result);
      } catch (Exception e) {
        continue;
      }
    }
    return valueMap;
  }