Java Class.getFields Examples

Java Class.getFields - 30 examples found. These are the top rated real world Java examples of Class.getFields extracted from open source projects. You can rate examples to help us improve the quality of examples.
Example #1
0
  /**
   * Create a default instance of every structure discovered in the thrift classes
   *
   * @param parsedThrift the container of everything discovered in the thrift generated classes.
   * @return an HashMap with key = structure name and value = structure default instance.
   * @throws InstantiationException
   * @throws IllegalAccessException
   * @throws NoSuchMethodException
   * @throws InvocationTargetException
   */
  private static HashMap<String, Object> getStructures(ParsedThrift parsedThrift)
      throws InstantiationException, IllegalAccessException, NoSuchMethodException,
          InvocationTargetException {
    HashMap<String, Object> result = new HashMap<String, Object>();

    for (String key : parsedThrift.structures.keySet()) {
      Class<?> structure = parsedThrift.structures.get(key);
      // First, find the structure's fields
      // aka the class members that implements TBase
      int arraySize =
          structure.getFields().length - 1; // expected number of fields, minus metadataMap
      Object[] defaults = new Object[arraySize];
      Class<?>[] constructorParameters = new Class<?>[arraySize];
      int i = 0; // let's party like it's 1994 !
      for (Field field : structure.getFields()) {
        if (!"metaDataMap".equalsIgnoreCase(field.getName())) {
          defaults[i] = Constants.defaultValue(field.getType());
          constructorParameters[i] = field.getType();
          i++;
        }
      }

      // Then, instantiate the structure
      Constructor constructor = structure.getConstructor(constructorParameters);
      Object instance = constructor.newInstance(defaults);
      result.put(key, instance);
    }

    return result;
  }
 /**
  * Discover default encodeables. Encodeables are discovered by inspecting all fields from
  * Identifiers class using reflection.
  *
  * @param map encodeable table to fill with builtin encodeables
  */
 @SuppressWarnings("unchecked")
 public static void discoverDefaultEncodeables(Map<NodeId, Class<IEncodeable>> map) {
   // Discover builtin classes
   Class<?> clazz = Identifiers.class;
   ClassLoader cl = clazz.getClassLoader();
   int index = clazz.getCanonicalName().lastIndexOf(".");
   String prefix = clazz.getCanonicalName().substring(0, index);
   for (Field f : clazz.getFields()) {
     f.setAccessible(true);
     try {
       String className = prefix + "." + f.getName();
       Class<IEncodeable> c = (Class<IEncodeable>) cl.loadClass(className);
       if (!IEncodeable.class.isAssignableFrom(c)) continue;
       for (Field cf : c.getFields()) {
         cf.setAccessible(true);
         if (!cf.getType().equals(NodeId.class)) continue;
         NodeId nodeId;
         try {
           nodeId = (NodeId) cf.get(null);
         } catch (IllegalArgumentException e) {
           throw new RuntimeException("Failed to load default identifiers", e);
         } catch (IllegalAccessException e) {
           throw new RuntimeException("Failed to load default identifiers", e);
         }
         if (nodeId == null) throw new RuntimeException("Failed to load default identifiers");
         map.put(nodeId, c);
       }
     } catch (ClassNotFoundException e) {
       continue;
     }
   }
 }
Example #3
0
 public static synchronized void registerClass(final Class c) {
   // Log.debug ("Registering stylekeys from " + c);
   try {
     final Field[] fields = c.getFields();
     for (int i = 0; i < fields.length; i++) {
       final Field field = fields[i];
       final int modifiers = field.getModifiers();
       if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
         if (Modifier.isFinal(modifiers) == false) {
           logger.warn("Invalid implementation: StyleKeys should be 'public static final': " + c);
         }
         if (field.getType().isAssignableFrom(StyleKey.class)) {
           //noinspection UnusedDeclaration
           final StyleKey value = (StyleKey) field.get(null);
           // ignore the returned value, all we want is to trigger the key
           // creation
           // Log.debug ("Loaded key " + value);
         }
       }
     }
   } catch (IllegalAccessException e) {
     // wont happen, we've checked it..
     logger.warn("Unable to register keys from " + c.getName());
   }
 }
  /**
   * Returns the values of all the public members in the specified object. The returned value has
   * the format: member1 = value1, member2 = value2, ...
   */
  public static String toStringPublicMembers(Object object) {
    if (object == null) {
      return null;
    }

    String retval = "";
    Class cls = object.getClass();
    Field fields[] = cls.getFields();
    String name;
    Object value;
    try {
      for (int i = 0; i < fields.length; i++) {
        name = fields[i].getName();
        value = fields[i].get(object);
        if (value instanceof byte[]) {
          value = new String((byte[]) value);
        } else if (value instanceof Byte) {
          value = ((Byte) value).toString();
        }
        retval += name + " = " + value + ", ";
      }
    } catch (IllegalAccessException ex) {
      ex.printStackTrace();
    }

    // Remove the trailing ", ".
    if (retval.length() > 0) {
      retval = retval.substring(0, retval.length() - 2);
    }
    return retval;
  }
  private void processClass(Class<?> someclass) {
    Field fields[] = someclass.getFields();

    for (int index = 0; index < fields.length; index++) {
      Field field = fields[index];

      // String mods = field.getModifiers();
      Class<?> fieldType = field.getType();
      String name = field.getName();

      Object value = null;
      try {
        if (Modifier.isStatic(field.getModifiers())) value = field.get(null);
      } catch (IllegalAccessException exc) {
        exc.printStackTrace();
      }

      if (fieldType.isArray()) {
        fireArrayBegin(fieldType, name);
        fireArrayEnd();
      } else {
        fireFieldFound(fieldType, name, value);
      }
    }
  }
  private void processObject(Object someObject) {
    Class<?> itsClass = someObject.getClass();
    Field fields[] = itsClass.getFields();

    for (int index = 0; index < fields.length; index++) {
      Field field = fields[index];

      // String mods = field.getModifiers();
      Class<?> fieldType = field.getType();
      String name = field.getName();

      try {
        if (fieldType.isArray()) {
          fireArrayBegin(fieldType, name);
          processArray(field.get(someObject));
          fireArrayEnd();
        } else {
          Object fieldValue = field.get(someObject);
          fireFieldFound(fieldType, name, fieldValue);
        }
      } catch (IllegalAccessException exc) {
        // as a debug for now
        exc.printStackTrace();
      }
    }
  }