/**
  * 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;
     }
   }
 }
Пример #2
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;
  }
Пример #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());
   }
 }
Пример #4
0
  /**
   * 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();
      }
    }
  }
  public EnumProperty(Class<E> e, JAXBContextImpl context) throws JAXBException {
    _enum = e;
    _typeName = JAXBUtil.getXmlSchemaDatatype(_enum, context);

    try {
      XmlEnum xmlEnum = _enum.getAnnotation(XmlEnum.class);
      _base = xmlEnum.value();
      _baseName = JAXBUtil.getXmlSchemaDatatype(_base, context);

      // XXX check that base is an XML simple type

      Field[] fields = _enum.getFields();

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

        // We only care about actual enum fields
        if (!fields[i].isEnumConstant()) continue;

        XmlEnumValue xmlEnumValue = f.getAnnotation(XmlEnumValue.class);
        E value = Enum.valueOf(_enum, f.getName());

        if (xmlEnumValue != null) {
          _valueMap.put(xmlEnumValue.value(), value);
          _nameMap.put(value, xmlEnumValue.value());
        } else {
          _valueMap.put(f.getName(), value);
          _nameMap.put(value, f.getName());
        }
      }
    } catch (Exception ex) {
      throw new JAXBException(L.l("Error while introspecting enum {0}", e.getName()), ex);
    }
  }
Пример #8
0
  public ArrayList<String> findClass(String expression) {
    ArrayList<String> classInfo = new ArrayList<String>();

    try {
      Class theClass = Thread.currentThread().getContextClassLoader().loadClass(expression);
      for (Field field : theClass.getFields()) {
        classInfo.add(field.getName() + "/" + expression + "/field/");
      }

      for (Method method : theClass.getMethods()) {
        StringBuffer paramStmt = new StringBuffer("(");
        String sep = "";
        for (Class paramCls : method.getParameterTypes()) {
          String clsNameOnly = UEngineUtil.getClassNameOnly(paramCls);
          clsNameOnly =
              sep
                  + clsNameOnly.substring(0, 1).toLowerCase()
                  + clsNameOnly.substring(1, clsNameOnly.length());
          paramStmt.append(clsNameOnly);
          sep = ", ";
        }
        paramStmt.append(")");

        classInfo.add(method.getName() + paramStmt + "/" + expression + "/method/");
      }
    } catch (Exception e) {
    }

    return classInfo;
  }
  private static String createTableString(Class<?> classTemplate) {

    String strMakeQuery = "create table ";
    strMakeQuery += classTemplate.getSimpleName() + " (";
    strMakeQuery += "ID INTEGER PRIMARY KEY AUTOINCREMENT, ";

    Field fieldArray[] = classTemplate.getFields();

    for (int field = 0, maxfield = fieldArray.length; field < maxfield; field++) {

      strMakeQuery += fieldArray[field].getName() + " ";

      if (fieldArray[field].getType() == int.class || fieldArray[field].getType() == long.class) {
        strMakeQuery += "INTEGER";
      } else if (fieldArray[field].getType() == String.class) {
        strMakeQuery += "TEXT";
      }

      if (field == maxfield - 1) {
        strMakeQuery += " ) ";
      } else {
        strMakeQuery += ", ";
      }
    }

    return strMakeQuery;
  }
Пример #10
0
  private static void readClassIds(
      Class<?> platformIdClass, String namespace, Map<String, Integer> namesToIds) {
    try {
      final Field[] fields = platformIdClass.getFields();
      for (int i = 0; i < fields.length; i++) {
        final Field field = fields[i];
        final int modifiers = field.getModifiers();
        if (Modifier.isStatic(modifiers)) {
          final Class fieldType = field.getType();
          if (fieldType == int.class) {
            final String name = field.getName();
            final int value = field.getInt(null);
            final String namespacedName;
            if (null == namespace) {
              namespacedName = name;
            } else {
              namespacedName = namespace + ":" + name;
            }

            namesToIds.put(namespacedName, value);
          }
        }
      }
    } catch (IllegalAccessException e) {
      Log.e(LOGTAG, "Can't read built-in id names from " + platformIdClass.getName(), e);
    }
  }
Пример #11
0
  public static List<? extends Map<String, ?>> getMapped(List<?> objects, String[] desired_fields) {
    ArrayList<Map<String, ?>> list = new ArrayList<Map<String, ?>>();
    for (Object object : objects) {
      HashMap<String, Object> map = new HashMap<String, Object>();
      Class<? extends Object> c = object.getClass();
      for (Field field : c.getFields()) {
        Annotation[] ann = (Annotation[]) field.getAnnotations();
        for (Annotation annotation : ann) {
          if (annotation instanceof Element || annotation instanceof Attribute) {
            try {
              boolean is_in = false;
              for (String desired_field : desired_fields) {
                if (desired_field.equals(field.getName())) {
                  is_in = true;
                  break;
                }
              }
              if (is_in) {
                map.put(field.getName(), field.get(object));
              }

            } catch (IllegalArgumentException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            } catch (IllegalAccessException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
        }
      }
      list.add(map);
    }
    return list;
  }
Пример #12
0
  @Override
  public boolean isItemValid(ItemStack par1ItemStack) {
    Class buildCraftClass = null;

    try {
      if ((buildCraftClass = Class.forName("buildcraft.BuildCraftEnergy")) != null) {
        for (final Field f : buildCraftClass.getFields()) {
          if (f.getName().equals("bucketOil")) {
            final Item item = (Item) f.get(null);

            if (par1ItemStack.itemID == item.itemID) {
              return true;
            }
          }
        }
      }
    } catch (final Throwable cnfe) {
    }

    if (par1ItemStack.getItem() instanceof GCCoreItemOilCanister
        && par1ItemStack.getItemDamage() > 0) {
      return true;
    }

    return false;
  }
Пример #13
0
  /** Return an entry from the property descrpitor cache for a class. */
  private PropertyDescriptorCacheEntry getPropertyDescriptorCacheEntry(Class c) {
    PropertyDescriptorCacheEntry pce =
        (PropertyDescriptorCacheEntry) propertyDescriptorCache.get(c);

    try {
      if (pce == null) {
        BeanInfo beanInfo = Introspector.getBeanInfo(c, stopClass);
        pce = new PropertyDescriptorCacheEntry();
        pce.propertyDescriptors = beanInfo.getPropertyDescriptors();
        pce.propertiesByName = createPropertiesByNameMap(pce.propertyDescriptors, c.getFields());
        if (cachePropertiesDescriptors) {
          synchronized (propertyDescriptorCache) {
            PropertyDescriptorCacheEntry pce2 =
                (PropertyDescriptorCacheEntry) propertyDescriptorCache.get(c);
            if (pce2 == null) propertyDescriptorCache.put(c, pce);
            else pce = pce2;
          }
        }
      }
    } catch (IntrospectionException ex) {
      // Log failed property set errors
      if (Log.isError()) {
        Logger log = Log.getLogger(LOG_CATEGORY);
        log.error(
            "Failed to introspect object of type: " + c + " error: " + ExceptionUtil.toString(ex));
      }

      // Return an empty descriptor rather than crashing
      pce = new PropertyDescriptorCacheEntry();
      pce.propertyDescriptors = new PropertyDescriptor[0];
      pce.propertiesByName = new TreeMap();
    }
    return pce;
  }
Пример #14
0
  /**
   * Runs the test using the specified harness.
   *
   * @param harness the test harness (<code>null</code> not permitted).
   */
  public void test(TestHarness harness) {
    // map of fields which should exists
    Map<String, String> testedFields = null;

    // map of fields for (Open)JDK6
    Map<String, String> testedFields_jdk6 = new HashMap<String, String>();

    // map of fields for (Open)JDK7
    Map<String, String> testedFields_jdk7 = new HashMap<String, String>();

    // map for fields declared in (Open)JDK6
    // --- empty ---

    // map for fields declared in (Open)JDK7
    // --- empty ---

    // create instance of a class UnsupportedOperationException
    final Object o = new UnsupportedOperationException("java.lang.UnsupportedOperationException");

    // get a runtime class of an object "o"
    final Class c = o.getClass();

    // get the right map containing field signatures
    testedFields = getJavaVersion() < 7 ? testedFields_jdk6 : testedFields_jdk7;

    // get all fields for this class
    java.lang.reflect.Field[] fields = c.getFields();

    // expected number of fields
    final int expectedNumberOfFields = testedFields.size();

    // basic check for a number of fields
    harness.check(fields.length, expectedNumberOfFields);
  }
Пример #15
0
  /**
   * *************************************************************************** Builds the grammar
   * from a class with parsing expression fields. The fields whose type is Expression (or one of its
   * subclasses) are converted to rules, using the field name as rule name. The root rule needs to
   * be held in a field named "root".
   *
   * <p>Mostly, building a grammar means building a proper expression graph from the class. When
   * modeling a grammar as a Java class, reference to other rules can be implemented as reference to
   * the field that holds the rule, but because of recursion, that alone doesn't suffice. Hence the
   * presence of reference expressions, to allow referencing a rule before its field gets declared.
   *
   * <p>With reference expressions, expressions form a graph. Once reference are resolved, this tree
   * becomes a graph. If there is some recursion in the grammar, this graph will contain loops.
   *
   * @see Expression.tidy()
   */
  public Grammar(Class<?> klass) {
    try {
      Object grammar = klass.newInstance();

      for (int i = 0; i < 2; ++i)
        for (Field field : klass.getFields()) {
          Object o = field.get(grammar);

          if (Rule.class.isAssignableFrom(o.getClass())) {
            Rule rule = (Rule) o;

            if (i == 1) {
              // always returns $rule
              cleaner.clean(rule);
            } else {
              if (rule.name == null) {
                setFinal(o, "name", field.getName());
              }
              registerRule(rule);
            }
          }
        }

      // If there is an initialize(grammar) method, call it.
      Method method = klass.getMethod("initialize", Grammar.class);
      method.invoke(grammar, this);
    } catch (NoSuchMethodException e) {
      /* ignore  (from getMethod()) */
    } catch (Exception e) {
      e.printStackTrace();
      throw new Error("Problem while extracting grammar rules " + "from class " + klass, e);
    }
  }
Пример #16
0
  private static void writeVariables(String _package, String _class, String _object)
      throws Exception {
    // out.printf( "\t//varaibles defined in %s%s (and its super classes/interfaces)\n\n", _package,
    // _class );

    Class gl_class = Class.forName(_package + _class);

    // Field[] fields = gl_class.getDeclaredFields(); // returns private fields

    Field[] fields = gl_class.getFields(); // only public fields

    for (Field f : fields) {
      String s = f.toString();

      int i1 = s.lastIndexOf(".");

      String s1 = s.substring(0, i1);

      int i2 = s1.lastIndexOf(' ');

      String s2 = s1.substring(0, i2);

      s1 = s1.substring(i2 + 1);

      out.printf("\t%s %s = %s.%s;\n", s2, f.getName(), s1, f.getName());
    }
  }
Пример #17
0
 public static Object jsonToObject(Class c, JSONObject json)
     throws JSONException, InstantiationException, IllegalAccessException {
   Object obj = c.newInstance();
   if (json == null) {
     return obj;
   } else {
     Field[] fields = c.getFields();
     Object value;
     for (int i = 0; i < fields.length; i++) {
       String fieldName = fields[i].getName();
       String methodName =
           "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
       if (ClassUtils.judgeClassType(fields[i].getClass())) {
         value = json.getString(fields[i].getName());
         ClassUtils.setMethodProxy(obj, methodName, new Object[] {value});
       } else {
         value = json.getJSONObject(fields[i].getName());
         ClassUtils.setMethodProxy(
             obj,
             methodName,
             new Object[] {jsonToObject(fields[i].getClass(), (JSONObject) value)});
       }
     }
   }
   return obj;
 }
Пример #18
0
  private void displayMetModels() {
    Class<?>[] modelClasses = Metadata.class.getInterfaces();
    Arrays.sort(
        modelClasses,
        new Comparator<Class<?>>() {
          public int compare(Class<?> o1, Class<?> o2) {
            return o1.getName().compareTo(o2.getName());
          }
        });

    for (Class<?> modelClass : modelClasses) {
      // we don't care about internal Tika met classes
      // if we do, then we can take this conditional out
      if (!modelClass.getSimpleName().contains("Tika")) {
        System.out.println(modelClass.getSimpleName());
        Field[] keyFields = modelClass.getFields();
        Arrays.sort(
            keyFields,
            new Comparator<Field>() {
              public int compare(Field o1, Field o2) {
                return o1.getName().compareTo(o2.getName());
              }
            });
        for (Field keyField : keyFields) {
          System.out.println(" " + keyField.getName());
        }
      }
    }
  }
Пример #19
0
  /** Looks inside the given class and finds all declared properties */
  protected static Property<?>[] generateProperties(Class<? extends AbstractModel> cls) {
    ArrayList<Property<?>> properties = new ArrayList<>();
    if (cls.getSuperclass() != AbstractModel.class) {
      properties.addAll(
          Arrays.asList(generateProperties((Class<? extends AbstractModel>) cls.getSuperclass())));
    }

    // a property is public, static & extends Property
    for (Field field : cls.getFields()) {
      if ((field.getModifiers() & Modifier.STATIC) == 0) {
        continue;
      }
      if (!Property.class.isAssignableFrom(field.getType())) {
        continue;
      }
      try {
        if (((Property<?>) field.get(null)).table == null) {
          continue;
        }
        properties.add((Property<?>) field.get(null));
      } catch (IllegalArgumentException | IllegalAccessException e) {
        throw new RuntimeException(e);
      }
    }

    return properties.toArray(new Property<?>[properties.size()]);
  }
Пример #20
0
  /**
   * use annotation based class parsing to detect the configurable properties of a <code>
   * Configurable</code>-class
   *
   * @param configurable of type Class
   */
  private static Map<Field, Annotation> parseClass(Class<? extends Configurable> configurable) {
    Field[] classFields = configurable.getFields();

    Map<Field, Annotation> s4props = new HashMap<Field, Annotation>();
    for (Field field : classFields) {
      Annotation[] annotations = field.getAnnotations();

      for (Annotation annotation : annotations) {
        Annotation[] superAnnotations = annotation.annotationType().getAnnotations();

        for (Annotation superAnnotation : superAnnotations) {
          if (superAnnotation instanceof S4Property) {
            int fieldModifiers = field.getModifiers();
            assert Modifier.isStatic(fieldModifiers) : "property fields are assumed to be static";
            assert Modifier.isPublic(fieldModifiers) : "property fields are assumed to be public";
            assert Modifier.isFinal(fieldModifiers) : "property fields are assumed to be final";
            assert field.getType().equals(String.class)
                : "properties fields are assumed to be instances of java.lang.String";

            s4props.put(field, annotation);
          }
        }
      }
    }

    return s4props;
  }
Пример #21
0
  public BinaryXMLParser(RootNode root) {
    try {
      try {
        Class<?> rStyleCls = Class.forName(ANDROID_R_STYLE_CLS);
        for (Field f : rStyleCls.getFields()) {
          styleMap.put(f.getInt(f.getType()), f.getName());
        }
      } catch (Throwable th) {
        LOG.error("R class loading failed", th);
      }
      // add application constants
      for (DexNode dexNode : root.getDexNodes()) {
        for (Map.Entry<Object, FieldNode> entry : dexNode.getConstFields().entrySet()) {
          Object key = entry.getKey();
          FieldNode field = entry.getValue();
          if (field.getType().equals(ArgType.INT) && key instanceof Integer) {
            localStyleMap.put((Integer) key, field);
          }
        }
      }

      resNames = root.getResourcesNames();

      attributes = new ManifestAttributes();
      attributes.parse();
    } catch (Exception e) {
      throw new JadxRuntimeException("BinaryXMLParser init error", e);
    }
  }
Пример #22
0
  public static File createBuildXML(
      String justepHome, String antLibDir, String nativeDir, AppInfo appInfo, String session)
      throws IOException, IllegalAccessException {
    File buildTmplFile = new File(antLibDir + "/build.xml");
    BufferedReader br =
        new BufferedReader(new InputStreamReader(new FileInputStream(buildTmplFile)));
    StringBuffer sb = new StringBuffer();
    String str = null;
    while ((str = br.readLine()) != null) sb.append(str + "\r\n");
    String content = sb.toString();
    // 文件中的占位标识为@value@,和ant的文本替换一致
    content = content.replace("@justepHome@", justepHome);
    content = content.replace("@antLibDir@", antLibDir);
    content = content.replace("@nativeDir@", nativeDir);
    content = content.replace("@session@", session);
    Class<? extends AppInfo> cls = appInfo.getClass();
    Field[] flds = cls.getFields();
    Object v;
    if (flds != null) {
      for (int i = 0; i < flds.length; i++) {
        v = flds[i].get(appInfo);
        content = content.replace("@" + flds[i].getName() + "@", v != null ? v.toString() : "");
      }
    }

    File buildFile = File.createTempFile("x5app-build", ".xml");
    buildFile.deleteOnExit();
    FileOutputStream buildFileStream = new FileOutputStream(buildFile);
    buildFileStream.write(content.getBytes("UTF-8"));
    br.close();
    buildFileStream.close();

    return buildFile;
  }
 @Override
 public void create(Record record, JsonNode json, Class clazz, String dir) throws Exception {
   for (Field f : clazz.getFields()) {
     if (!json.has(f.getName())) return;
     JsonNode j = json.get(f.getName());
     JsonField field = f.getAnnotation(JsonField.class);
     JsonStruc struc = f.getAnnotation(JsonStruc.class);
     if (field != null) {
       SubRecordData sub = record.get(field.value()[0]);
       if (f.getType() == String.class) ((SubZString) sub).value = j.asText();
       else if (f.getType() == JsonFile.class)
         ((SubZString) sub).value =
             (j.asText().startsWith("/") ? j.asText().substring(1) : dir + "/" + j.asText())
                 .replace("/", "\\");
       else if (f.getType() == int[].class)
         for (int i = 0; i < sub.size(); i++) ((SubIntArray) sub).value[i] = j.get(i).intValue();
       else if (f.getType() == JsonFormID[].class) {
         if (field.value()[1] != null) record.get(field.value()[1]);
         ((SubFormIDList) sub).value.clear();
         for (int i = 0; i < sub.size(); i++)
           ((SubFormIDList) sub).value.add(getFormId(j.get(i), field.value(), 2));
       }
     }
     if (struc != null) {
       SubRecordData sub = record.get(struc.value()[0]);
       Field subf = sub.getClass().getField(struc.value()[1]);
       if (f.getType() == int.class) subf.setInt(sub, j.asInt());
       else if (f.getType() == float.class) subf.setFloat(sub, (float) j.asDouble());
     }
   }
 }
Пример #24
0
 public static void printFields(Class<?> javaClass) {
   final String className = javaClass.getSimpleName();
   TTY.println(className + " {");
   for (final Field field : javaClass.getFields()) {
     printField(field, false);
   }
   TTY.println("}");
 }
Пример #25
0
  /**
   * すべてのメンバを表示する
   *
   * @param Class<?> c メンバを表示したいクラス型オブジェクト
   */
  public static void printAllMembers(Class<?> c) {
    System.out.println("クラス: ");
    System.out.println(c);

    System.out.println("フィールド: ");
    Field[] declaredfields = c.getDeclaredFields();
    Field[] fields = c.getFields();
    ArrayList<Field> fieldList = new ArrayList<Field>(fields.length);
    for (int i = 0; i < fields.length; i++) {
      fieldList.add(fields[i]);
    }
    for (int i = 0; i < declaredfields.length; i++) {
      if (!fieldList.contains(declaredfields[i])) {
        fieldList.add(declaredfields[i]);
      }
    }
    Field[] allFields = new Field[fieldList.size()];
    for (int i = 0; i < allFields.length; i++) {
      allFields[i] = fieldList.get(i);
    }
    printMembers(allFields);

    System.out.println("コンストラクタ: ");
    Constructor[] declaredconstructors = c.getDeclaredConstructors();
    Constructor[] constructors = c.getConstructors();
    ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length);
    for (int i = 0; i < constructors.length; i++) {
      constructorList.add(constructors[i]);
    }
    for (int i = 0; i < declaredconstructors.length; i++) {
      if (!constructorList.contains(declaredconstructors[i])) {
        constructorList.add(declaredconstructors[i]);
      }
    }
    Constructor[] allConstructors = new Constructor[constructorList.size()];
    for (int i = 0; i < allConstructors.length; i++) {
      allConstructors[i] = constructorList.get(i);
    }
    printMembers(allConstructors);

    System.out.println("メソッド: ");
    Method[] declaredmethods = c.getDeclaredMethods();
    Method[] methods = c.getMethods();
    ArrayList<Method> methodList = new ArrayList<Method>(methods.length);
    for (int i = 0; i < methods.length; i++) {
      methodList.add(methods[i]);
    }
    for (int i = 0; i < declaredmethods.length; i++) {
      if (!methodList.contains(declaredmethods[i])) {
        methodList.add(declaredmethods[i]);
      }
    }
    Method[] allMethods = new Method[methodList.size()];
    for (int i = 0; i < allMethods.length; i++) {
      allMethods[i] = methodList.get(i);
    }
    printMembers(allMethods);
  }
Пример #26
0
 private static Field findField(Class<?> target, String fieldName) {
   Field[] fields = target.getFields();
   for (Field field : fields) {
     if (fieldName.equals(field.getName())) {
       return field;
     }
   }
   return null;
 }
 private Field columnNameToField(Class<?> clazz, String columnName) {
   for (Field field : clazz.getFields()) {
     Column column = field.getAnnotation(Column.class);
     if (equalsIgnoreCase(columnName, column.name())) {
       return field;
     }
   }
   return null;
 }
  protected static void init(SCSession session, Class<? extends SCKeynodesBase> klass) {
    if (log.isDebugEnabled()) log.debug("Start retrieving keynodes for " + klass);

    try {
      //
      // Search default segment for keynodes
      //
      SCSegment defaultSegment = null;
      {
        DefaultSegment annotation = klass.getAnnotation(DefaultSegment.class);
        if (annotation != null) {
          defaultSegment = session.openSegment(annotation.value());
          Validate.notNull(defaultSegment, "Default segment \"{0}\" not found", annotation.value());
          klass.getField(annotation.fieldName()).set(null, defaultSegment);
        }
      }

      Field[] fields = klass.getFields();
      for (Field field : fields) {
        int modifiers = field.getModifiers();

        if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
          Class<?> type = field.getType();
          if (type.equals(SCSegment.class)) {
            //
            // We have segment field. Load segment by uri.
            //
            SegmentURI annotation = field.getAnnotation(SegmentURI.class);

            if (annotation != null) {
              String uri = annotation.value();
              SCSegment segment = session.openSegment(uri);
              field.set(null, segment);
            } else {
              // May be it already has value?
              if (log.isWarnEnabled()) {
                if (field.get(null) == null) log.warn(field + " doesn't have value");
              }
            }
          } else {
            if (!(checkKeynode(session, defaultSegment, field)
                || checkKeynodeURI(session, field)
                || checkKeynodesNumberPatternURI(session, klass, field))) {

              if (log.isWarnEnabled()) {
                if (field.get(null) == null)
                  log.warn(field + " doesn't have annotations and value");
              }
            }
          }
        }
      }
    } catch (Exception e) {
      // TODO: handle
      e.printStackTrace();
    }
  }
Пример #29
0
 /**
  * store a class with his methods
  *
  * @param clazz
  * @return returns stored Struct
  */
 private StructImpl store(Class clazz) {
   Field[] fieldsArr = clazz.getFields();
   StructImpl fieldsMap = new StructImpl();
   for (int i = 0; i < fieldsArr.length; i++) {
     storeField(fieldsArr[i], fieldsMap);
   }
   map.put(clazz, fieldsMap);
   return fieldsMap;
 }
  public DistributionSettingMap(Class<? extends IOreDistribution> distributionType) {
    for (Field field : distributionType.getFields()) {
      DistributionSetting s = (DistributionSetting) field.getAnnotation(DistributionSetting.class);

      if (s != null) {
        this._settingMap.put(s.name(), new Object[] {field, s});
      }
    }
  }