java.lang.Class.getFields()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(9.3k)|赞(0)|评价(0)|浏览(262)

本文整理了Java中java.lang.Class.getFields()方法的一些代码示例,展示了Class.getFields()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Class.getFields()方法的具体详情如下:
包路径:java.lang.Class
类名称:Class
方法名:getFields

Class.getFields介绍

[英]Returns an array containing Field objects for all public fields for the class C represented by this Class. Fields may be declared in C, the interfaces it implements or in the superclasses of C. The elements in the returned array are in no particular order.

If there are no public fields or if this class represents an array class, a primitive type or void then an empty array is returned.
[中]返回一个数组,该数组包含该类表示的类C的所有公共字段的字段对象。字段可以在C、它实现的接口或C的超类中声明。返回数组中的元素没有特定顺序。
如果没有公共字段,或者该类表示数组类、基元类型或void,则返回空数组。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private static void ensureSpringRulesAreNotPresent(Class<?> testClass) {
  for (Field field : testClass.getFields()) {
    Assert.state(!SpringClassRule.class.isAssignableFrom(field.getType()), () -> String.format(
        "Detected SpringClassRule field in test class [%s], " +
        "but SpringClassRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
    Assert.state(!SpringMethodRule.class.isAssignableFrom(field.getType()), () -> String.format(
        "Detected SpringMethodRule field in test class [%s], " +
        "but SpringMethodRule cannot be used with the SpringJUnit4ClassRunner.", testClass.getName()));
  }
}

代码示例来源:origin: skylot/jadx

private void readAndroidRStyleClass() {
  try {
    Class<?> rStyleCls = Class.forName(ANDROID_R_STYLE_CLS);
    for (Field f : rStyleCls.getFields()) {
      styleMap.put(f.getInt(f.getType()), f.getName());
    }
  } catch (Exception th) {
    LOG.error("Android R class loading failed", th);
  }
}

代码示例来源:origin: spring-projects/spring-loaded

public static List<Field> callGetFields(Class thiz)
throws SecurityException
{
  return Arrays.asList(thiz.getFields());
}

代码示例来源:origin: stackoverflow.com

public void listRaw(){
  Field[] fields=R.raw.class.getFields();
  for(int count=0; count < fields.length; count++){
    Log.i("Raw Asset: ", fields[count].getName());
  }
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Go through all of the paths via reflection, and print them out in a TSV format.
 * This is useful for command line scripts.
 *
 * @param args Ignored.
 */
public static void main(String[] args) throws IllegalAccessException {
 for (Field field : DefaultPaths.class.getFields()) {
  System.out.println(field.getName() + "\t" + field.get(null));
 }
}

代码示例来源:origin: stanfordnlp/CoreNLP

/**
 * Go through all of the paths via reflection, and print them out in a TSV format.
 * This is useful for command line scripts.
 *
 * @param args Ignored.
 */
public static void main(String[] args) throws IllegalAccessException {
 for (Field field : LanguageInfo.class.getFields()) {
  System.out.println(field.getName() + "\t" + field.get(null));
 }
}

代码示例来源:origin: apache/flink

private int countFieldsInClass(Class<?> clazz) {
  int fieldCount = 0;
  for(Field field : clazz.getFields()) { // get all fields
    if(	!Modifier.isStatic(field.getModifiers()) &&
      !Modifier.isTransient(field.getModifiers())
      ) {
      fieldCount++;
    }
  }
  return fieldCount;
}

代码示例来源:origin: libgdx/libgdx

/** Returns an array of {@link Field} containing the public fields of the class represented by the supplied Class. */
static public Field[] getFields (Class c) {
  java.lang.reflect.Field[] fields = c.getFields();
  Field[] result = new Field[fields.length];
  for (int i = 0, j = fields.length; i < j; i++) {
    result[i] = new Field(fields[i]);
  }
  return result;
}

代码示例来源:origin: libgdx/libgdx

/** Returns an array of {@link Field} containing the public fields of the class represented by the supplied Class. */
static public Field[] getFields (Class c) {
  java.lang.reflect.Field[] fields = c.getFields();
  Field[] result = new Field[fields.length];
  for (int i = 0, j = fields.length; i < j; i++) {
    result[i] = new Field(fields[i]);
  }
  return result;
}

代码示例来源:origin: stackoverflow.com

for (Field f: MyClass.class.getFields()) {
  Column column = f.getAnnotation(Column.class);
  if (column != null)
    System.out.println(column.columnName());
}

代码示例来源:origin: pxb1988/dex2jar

public static void main(String... strings) throws IllegalArgumentException, IllegalAccessException {
  for (Field f : SectionItem.class.getFields()) {
    if (f.getType().equals(int.class)) {
      if (0 != (f.getModifiers() & Modifier.STATIC)) {
        System.out.printf("%s(0x%04x,0,0),//\n", f.getName(), f.get(null));
      }
    }
  }
}

代码示例来源:origin: apache/storm

private static String getSqlTypeName(int sqlType) {
  try {
    Integer val = new Integer(sqlType);
    for (Field field : Types.class.getFields()) {
      if (val.equals(field.get(null))) {
        return field.getName();
      }
    }
  } catch (IllegalAccessException e) {
    throw new RuntimeException("Could not get sqlTypeName ", e);
  }
  throw new RuntimeException("Unknown sqlType " + sqlType);
}

代码示例来源:origin: jenkinsci/jenkins

/**
 * Given the class, list up its {@link PropertyType}s from its public fields/getters.
 */
private Map<String, PropertyType> buildPropertyTypes(Class<?> clazz) {
  Map<String, PropertyType> r = new HashMap<String, PropertyType>();
  for (Field f : clazz.getFields())
    r.put(f.getName(),new PropertyType(f));
  for (Method m : clazz.getMethods())
    if(m.getName().startsWith("get"))
      r.put(Introspector.decapitalize(m.getName().substring(3)),new PropertyType(m));
  return r;
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Create a new Constants converter class wrapping the given class.
 * <p>All <b>public</b> static final variables will be exposed, whatever their type.
 * @param clazz the class to analyze
 * @throws IllegalArgumentException if the supplied {@code clazz} is {@code null}
 */
public Constants(Class<?> clazz) {
  Assert.notNull(clazz, "Class must not be null");
  this.className = clazz.getName();
  Field[] fields = clazz.getFields();
  for (Field field : fields) {
    if (ReflectionUtils.isPublicStaticFinal(field)) {
      String name = field.getName();
      try {
        Object value = field.get(null);
        this.fieldCache.put(name, value);
      }
      catch (IllegalAccessException ex) {
        // just leave this field and continue
      }
    }
  }
}

代码示例来源:origin: apache/incubator-dubbo

private static Field getField(Class<?> cls, String fieldName) {
  Field result = null;
  if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) {
    return CLASS_FIELD_CACHE.get(cls).get(fieldName);
  }
  try {
    result = cls.getDeclaredField(fieldName);
    result.setAccessible(true);
  } catch (NoSuchFieldException e) {
    for (Field field : cls.getFields()) {
      if (fieldName.equals(field.getName()) && ReflectUtils.isPublicInstanceField(field)) {
        result = field;
        break;
      }
    }
  }
  if (result != null) {
    ConcurrentMap<String, Field> fields = CLASS_FIELD_CACHE.get(cls);
    if (fields == null) {
      fields = new ConcurrentHashMap<String, Field>();
      CLASS_FIELD_CACHE.putIfAbsent(cls, fields);
    }
    fields = CLASS_FIELD_CACHE.get(cls);
    fields.putIfAbsent(fieldName, result);
  }
  return result;
}

代码示例来源:origin: apache/incubator-dubbo

private static Field getField(Class<?> cls, String fieldName) {
  Field result = null;
  if (CLASS_FIELD_CACHE.containsKey(cls) && CLASS_FIELD_CACHE.get(cls).containsKey(fieldName)) {
    return CLASS_FIELD_CACHE.get(cls).get(fieldName);
  }
  try {
    result = cls.getDeclaredField(fieldName);
    result.setAccessible(true);
  } catch (NoSuchFieldException e) {
    for (Field field : cls.getFields()) {
      if (fieldName.equals(field.getName()) && ReflectUtils.isPublicInstanceField(field)) {
        result = field;
        break;
      }
    }
  }
  if (result != null) {
    ConcurrentMap<String, Field> fields = CLASS_FIELD_CACHE.get(cls);
    if (fields == null) {
      fields = new ConcurrentHashMap<String, Field>();
      CLASS_FIELD_CACHE.putIfAbsent(cls, fields);
    }
    fields = CLASS_FIELD_CACHE.get(cls);
    fields.putIfAbsent(fieldName, result);
  }
  return result;
}

代码示例来源:origin: spring-projects/spring-framework

/**
 * Find a field of a certain name on a specified class.
 */
@Nullable
protected Field findField(String name, Class<?> clazz, boolean mustBeStatic) {
  Field[] fields = clazz.getFields();
  for (Field field : fields) {
    if (field.getName().equals(name) && (!mustBeStatic || Modifier.isStatic(field.getModifiers()))) {
      return field;
    }
  }
  // We'll search superclasses and implemented interfaces explicitly,
  // although it shouldn't be necessary - however, see SPR-10125.
  if (clazz.getSuperclass() != null) {
    Field field = findField(name, clazz.getSuperclass(), mustBeStatic);
    if (field != null) {
      return field;
    }
  }
  for (Class<?> implementedInterface : clazz.getInterfaces()) {
    Field field = findField(name, implementedInterface, mustBeStatic);
    if (field != null) {
      return field;
    }
  }
  return null;
}

代码示例来源:origin: jfinal/jfinal

public FieldGetter takeOver(Class<?> targetClass, String fieldName) {
  java.lang.reflect.Field[] fieldArray = targetClass.getFields();
  for (java.lang.reflect.Field field : fieldArray) {
    if (field.getName().equals(fieldName)) {
      return new RealFieldGetter(field);
    }
  }
  
  return null;
}

代码示例来源:origin: apache/flink

static List<OptionWithMetaInfo> extractConfigOptions(Class<?> clazz) {
  try {
    List<OptionWithMetaInfo> configOptions = new ArrayList<>(8);
    Field[] fields = clazz.getFields();
    for (Field field : fields) {
      if (isConfigOption(field) && shouldBeDocumented(field)) {
        configOptions.add(new OptionWithMetaInfo((ConfigOption<?>) field.get(null), field));
      }
    }
    return configOptions;
  } catch (Exception e) {
    throw new RuntimeException("Failed to extract config options from class " + clazz + '.', e);
  }
}

代码示例来源:origin: jenkinsci/jenkins

private ParsedQuickSilver(Class<? extends SearchableModelObject> clazz) {
  QuickSilver qs;
  for (Method m : clazz.getMethods()) {
    qs = m.getAnnotation(QuickSilver.class);
    if(qs!=null) {
      String url = stripGetPrefix(m);
      if(qs.value().length==0)
        getters.add(new MethodGetter(url,splitName(url),m));
      else {
        for (String name : qs.value())
          getters.add(new MethodGetter(url,name,m));
      }
    }
  }
  for (Field f : clazz.getFields()) {
    qs = f.getAnnotation(QuickSilver.class);
    if(qs!=null) {
      if(qs.value().length==0)
        getters.add(new FieldGetter(f.getName(),splitName(f.getName()),f));
      else {
        for (String name : qs.value())
          getters.add(new FieldGetter(f.getName(),name,f));
      }
    }
  }
}

相关文章

微信公众号

最新文章

更多

Class类方法