Example usage for java.lang.reflect Field getName

List of usage examples for java.lang.reflect Field getName

Introduction

In this page you can find the example usage for java.lang.reflect Field getName.

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Gets all fields from a class. Keys are the field names as strings.
 *
 * @param type the type//from w ww. j  a  v  a 2s. c om
 * @return the all fields
 */
//CHECKSTYLE.OFF FinalParameter Precondition cast.
public static Map<String, Field> getAllFields(final Class<?> type) {

    Map<String, Field> fieldMap = new HashMap<>();
    for (Field field : type.getDeclaredFields()) {
        fieldMap.put(field.getName(), field);
    }
    Class<?> nextType = type.getSuperclass();

    while (nextType != Object.class) {
        for (Field field : nextType.getDeclaredFields()) {
            fieldMap.put(field.getName(), field);
        }
        nextType = nextType.getSuperclass();
    }
    //CHECKSTYLE.ON
    return fieldMap;
}

From source file:org.chorusbdd.chorus.spring.SpringContextInjector.java

private static void injectResourceFields(ApplicationContext springContext, Object handler, Class handlerClass) {
    ChorusLog log = ChorusLogFactory.getLog(SpringContextInjector.class);

    //inject handler fields with the Spring beans
    Field[] fields = handlerClass.getDeclaredFields();
    for (Field field : fields) {
        Resource resourceAnnotation = field.getAnnotation(Resource.class);
        if (resourceAnnotation != null) {
            boolean beanNameInAnnotation = !"".equals(resourceAnnotation.name());
            String name = beanNameInAnnotation ? resourceAnnotation.name() : field.getName();
            Object bean = springContext.getBean(name);
            log.trace("Found spring Resource annotation for field " + field
                    + " will attempt to inject Spring bean " + bean);
            if (bean == null) {
                log.error(//ww  w  .j a va 2s  .com
                        "Failed to set @Resource (" + name + "). No such bean exists in application context.");
            }
            try {
                field.setAccessible(true);
                field.set(handler, bean);
            } catch (IllegalAccessException e) {
                log.error("Failed to set @Resource (" + name + ") with bean of type: " + bean.getClass(), e);
            }
        }
    }

    Class superclass = handlerClass.getSuperclass();
    if (superclass != Object.class) {
        injectResourceFields(springContext, handler, superclass);
    }
}

From source file:common.utils.ReflectionAssert.java

/**
 * All fields that have a getter with the same name will be checked by an assertNotNull.
 * Other fields will be ignored/*from   w w  w .  ja v  a 2 s.com*/
 * 
 * @param message
 * @param object
 */
public static void assertAccessablePropertiesNotNull(String message, Object object) {

    Set<Field> fields = ReflectionUtils.getAllFields(object.getClass());
    for (Field field : fields) {
        Method getter = ReflectionUtils.getGetter(object.getClass(), field.getName(), false);
        if (getter != null) {
            Object result = null;

            try {
                result = getter.invoke(object, ArrayUtils.EMPTY_OBJECT_ARRAY);
            } catch (Exception e) {
                throw new UnitilsException(e);
            }
            String formattedMessage = formatMessage(message,
                    "Property '" + field.getName() + "' in object '" + object.toString() + "' is null ");
            assertNotNull(formattedMessage, result);
        }

    }
}

From source file:com.stratio.deep.es.utils.UtilES.java

/**
 * converts from an entity class with deep's anotations to JSONObject.
 *
 * @param t   an instance of an object of type T to convert to JSONObject.
 * @param <T> the type of the object to convert.
 * @return the provided object converted to JSONObject.
 * @throws IllegalAccessException//from  www. j  a v a2s. co m
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> JSONObject getJsonFromObject(T t)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Field[] fields = AnnotationUtils.filterDeepFields(t.getClass());

    JSONObject json = new JSONObject();

    for (Field field : fields) {
        Method method = Utils.findGetter(field.getName(), t.getClass());
        Object object = method.invoke(t);
        if (object != null) {
            if (Collection.class.isAssignableFrom(field.getType())) {
                Collection c = (Collection) object;
                Iterator iterator = c.iterator();
                List<JSONObject> innerJsonList = new ArrayList<>();

                while (iterator.hasNext()) {
                    innerJsonList.add(getJsonFromObject((IDeepType) iterator.next()));
                }
                json.put(AnnotationUtils.deepFieldName(field), innerJsonList);
            } else if (IDeepType.class.isAssignableFrom(field.getType())) {
                json.put(AnnotationUtils.deepFieldName(field), getJsonFromObject((IDeepType) object));
            } else {
                json.put(AnnotationUtils.deepFieldName(field), object);
            }
        }
    }

    return json;
}

From source file:org.mstc.zmq.json.Encoder.java

public static String encode(Object o) throws IOException {
    StringWriter writer = new StringWriter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    JsonFactory factory = mapper.getFactory();
    try (JsonGenerator g = factory.createGenerator(writer)) {
        g.writeStartObject();/* ww w.j  a  v a2s.c  o m*/
        for (Field f : o.getClass().getDeclaredFields()) {
            try {
                f.setAccessible(true);
                Object value = f.get(o);
                if (value != null) {
                    if (f.getType().isAssignableFrom(List.class)) {
                        String items = mapper.writeValueAsString(value);
                        g.writeStringField(f.getName(), items);
                    } else if (f.getType().isArray()) {
                        if (f.getType().getComponentType().isAssignableFrom(byte.class)) {
                            g.writeBinaryField(f.getName(), (byte[]) value);
                        } else {
                            int length = Array.getLength(value);
                            g.writeFieldName(f.getName());
                            g.writeStartArray();
                            for (int i = 0; i < length; i++) {
                                Object av = Array.get(value, i);
                                if (av instanceof Double) {
                                    g.writeNumber(new BigDecimal((Double) av).toPlainString());
                                } else if (av instanceof Float) {
                                    g.writeNumber(new BigDecimal((Float) av).toPlainString());
                                } else if (av instanceof Integer) {
                                    g.writeNumber(new BigDecimal((Integer) av).toPlainString());
                                } else {
                                    g.writeObject(av);
                                }
                                /*if (av instanceof Double)
                                g.writeNumber(new BigDecimal((Double) av));
                                else if (av instanceof Float)
                                g.writeNumber(new BigDecimal((Float) av));
                                else if (av instanceof Integer)
                                g.writeNumber((Integer) av);*/
                            }
                            g.writeEndArray();
                        }
                    } else {
                        g.writeObjectField(f.getName(), value);
                    }
                }

            } catch (IllegalAccessException e) {
                logger.warn("Could not get field: {}", f.getName(), e);
            }
        }
        g.writeEndObject();
    }
    if (logger.isDebugEnabled())
        logger.debug(writer.toString());
    return writer.toString();
}

From source file:ReflectUtil.java

/**
 * Fetches all fields of all access types from the supplied class and super
 * classes. Fieldss that have been overridden in the inheritance hierarchy are
 * only returned once, using the instance lowest down the hierarchy.
 *
 * @param clazz the class to inspect/*  w  w w . j a v  a  2s.  co m*/
 * @return a collection of fields
 */
public static Collection<Field> getFields(Class<?> clazz) {
    Map<String, Field> fields = new HashMap<String, Field>();
    while (clazz != null) {
        for (Field field : clazz.getDeclaredFields()) {
            if (!fields.containsKey(field.getName())) {
                fields.put(field.getName(), field);
            }
        }

        clazz = clazz.getSuperclass();
    }

    return fields.values();
}

From source file:com.stratio.deep.es.utils.UtilES.java

/**
 * converts from an entity class with deep's anotations to JSONObject.
 *
 * @param t   an instance of an object of type T to convert to JSONObject.
 * @param <T> the type of the object to convert.
 * @return the provided object converted to JSONObject.
 * @throws IllegalAccessException/*from  w  w  w .  j a va  2s . c o m*/
 * @throws InstantiationException
 * @throws InvocationTargetException
 */
public static <T> LinkedMapWritable getLinkedMapWritableFromObject(T t)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Field[] fields = AnnotationUtils.filterDeepFields(t.getClass());

    LinkedMapWritable linkedMapWritable = new LinkedMapWritable();

    for (Field field : fields) {
        Method method = Utils.findGetter(field.getName(), t.getClass());
        Object object = method.invoke(t);
        if (object != null) {
            if (Collection.class.isAssignableFrom(field.getType())) {
                Collection c = (Collection) object;
                Iterator iterator = c.iterator();
                List<LinkedMapWritable> innerJsonList = new ArrayList<>();

                while (iterator.hasNext()) {
                    innerJsonList.add(getLinkedMapWritableFromObject((IDeepType) iterator.next()));
                }
                // linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)), new
                // LinkedMapWritable[innerJsonList.size()]);
            } else if (IDeepType.class.isAssignableFrom(field.getType())) {
                linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)),
                        getLinkedMapWritableFromObject((IDeepType) object));
            } else {
                linkedMapWritable.put(new Text(AnnotationUtils.deepFieldName(field)),
                        getWritableFromObject(object));
            }
        }
    }

    return linkedMapWritable;
}

From source file:de.codesourcery.luaparser.LuaToJSON.java

private static int getOffset(JSONTokener tokener)
        throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {

    for (Field f : JSONTokener.class.getDeclaredFields()) {
        if (f.getName().equals("index")) {
            f.setAccessible(true);// w ww  .jav a2 s  . com
            return ((Number) f.get(tokener)).intValue();
        }
    }
    throw new RuntimeException("Internal error,failed to find field 'index' in JSONTokener");
}

From source file:com.antsdb.saltedfish.util.UberUtil.java

/**
 * warning, this method has no consideration of performance. it is written to help logging objects
 * /*  w w w.  j av  a 2  s.  co  m*/
 * @param obj
 * @return
 */
public static String toString(Object obj) {
    if (obj == null) {
        return "NULL";
    }
    StringBuilder buf = new StringBuilder();
    for (Field i : obj.getClass().getFields()) {
        if ((i.getModifiers() & Modifier.STATIC) != 0) {
            continue;
        }
        buf.append(i.getName());
        buf.append(":");
        Object value;
        try {
            value = i.get(obj);
        } catch (Exception x) {
            value = x.getMessage();
        }
        if (value != null) {
            buf.append(value.toString());
        } else {
            buf.append("NULL");
        }
        buf.append('\n');
    }
    return buf.toString();
}

From source file:net.minecraftforge.common.util.EnumHelper.java

@SuppressWarnings({ "unchecked", "serial" })
@Nullable/*  w w w.ja  va 2  s  .  c  o m*/
private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName,
        final Class<?>[] paramTypes, @Nullable Object[] paramValues) {
    if (!isSetup) {
        setup();
    }

    Field valuesField = null;
    Field[] fields = enumType.getDeclaredFields();

    for (Field field : fields) {
        String name = field.getName();
        if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
        {
            valuesField = field;
            break;
        }
    }

    int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC
            | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
    if (valuesField == null) {
        String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));

        for (Field field : fields) {
            if ((field.getModifiers() & flags) == flags
                    && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
            {
                valuesField = field;
                break;
            }
        }
    }

    if (valuesField == null) {
        final List<String> lines = Lists.newArrayList();
        lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
        lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
        lines.add(String.format("Flags: %s",
                String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
        lines.add("Fields:");
        for (Field field : fields) {
            String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
            lines.add(String.format("       %s %s: %s", mods, field.getName(), field.getType().getName()));
        }

        for (String line : lines)
            FMLLog.log.fatal(line);

        if (test) {
            throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) {
                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    for (String line : lines)
                        stream.println(line);
                }
            };
        }
        return null;
    }

    if (test) {
        Object ctr = null;
        Exception ex = null;
        try {
            ctr = getConstructorAccessor(enumType, paramTypes);
        } catch (Exception e) {
            ex = e;
        }
        if (ctr == null || ex != null) {
            throw new EnhancedRuntimeException(
                    String.format("Could not find constructor for Enum %s", enumType.getName()), ex) {
                private String toString(Class<?>[] cls) {
                    StringBuilder b = new StringBuilder();
                    for (int x = 0; x < cls.length; x++) {
                        b.append(cls[x].getName());
                        if (x != cls.length - 1)
                            b.append(", ");
                    }
                    return b.toString();
                }

                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    stream.println("Target Arguments:");
                    stream.println("    java.lang.String, int, " + toString(paramTypes));
                    stream.println("Found Constructors:");
                    for (Constructor<?> ctr : enumType.getDeclaredConstructors()) {
                        stream.println("    " + toString(ctr.getParameterTypes()));
                    }
                }
            };
        }
        return null;
    }

    valuesField.setAccessible(true);

    try {
        T[] previousValues = (T[]) valuesField.get(enumType);
        T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
        setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
        cleanEnumCache(enumType);

        return newValue;
    } catch (Exception e) {
        FMLLog.log.error("Error adding enum with EnumHelper.", e);
        throw new RuntimeException(e);
    }
}