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:org.querybyexample.jpa.JpaUtil.java

public static <T extends Identifiable<?>> String compositePkPropertyName(T entity) {
    for (Method m : entity.getClass().getMethods()) {
        if (m.getAnnotation(EmbeddedId.class) != null) {
            return BeanUtils.findPropertyForMethod(m).getName();
        }//w  ww. j a va 2s .  co m
    }
    for (Field f : entity.getClass().getFields()) {
        if (f.getAnnotation(EmbeddedId.class) != null) {
            return f.getName();
        }
    }
    return null;
}

From source file:edu.mayo.cts2.framework.model.util.ModelUtils.java

public static ChangeableResource createChangeableResource(IsChangeable changeable) {
    ChangeableResource choice = new ChangeableResource();

    for (Field field : choice.getClass().getDeclaredFields()) {
        if (field.getType().equals(changeable.getClass()) || field.getName().equals("_choiceValue")) {
            field.setAccessible(true);//  ww w  .ja v a  2 s.  co m
            try {
                field.set(choice, changeable);
            } catch (IllegalArgumentException e) {
                throw new IllegalStateException(e);
            } catch (IllegalAccessException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    return choice;
}

From source file:ch.ralscha.extdirectspring.generator.association.AbstractAssociation.java

private static String getWarningText(Field field, String type, String propertyName) {
    String warning = "Field ";
    warning += field.getDeclaringClass().getName();
    warning += ".";
    warning += field.getName();
    return warning + ": A '" + type + "' association does not support property '" + propertyName
            + "'. Property will be ignored.";
}

From source file:com.oembedler.moon.graphql.engine.dfs.ResolvableTypeAccessor.java

public static ResolvableTypeAccessor forField(Field field, Class<?> implClass) {
    ResolvableType resolvableType = ResolvableType.forField(field, implClass);
    return new ResolvableTypeAccessor(field.getName(), resolvableType,
            Lists.newArrayList(field.getAnnotations()), implClass);
}

From source file:com.adobe.acs.commons.mcp.util.AnnotatedFieldDeserializer.java

@SuppressWarnings("squid:S3776")
private static void parseInput(Object target, ValueMap input, Field field)
        throws ReflectiveOperationException, ParseException {
    FormField inputAnnotation = field.getAnnotation(FormField.class);
    Object value;/* w w w  .j a v a 2s .  com*/
    if (input.get(field.getName()) == null) {
        if (inputAnnotation != null && inputAnnotation.required()) {
            if (field.getType() == Boolean.class || field.getType() == Boolean.TYPE) {
                value = false;
            } else {
                throw new NullPointerException("Required field missing: " + field.getName());
            }
        } else {
            return;
        }
    } else {
        value = input.get(field.getName());
    }

    if (hasMultipleValues(field.getType())) {
        parseInputList(target, serializeToStringArray(value), field);
    } else {
        Object val = value;
        if (value.getClass().isArray()) {
            val = ((Object[]) value)[0];
        }

        if (val instanceof RequestParameter) {
            /** Special case handling uploaded files; Method call ~ copied from parseInputValue(..) **/
            if (field.getType() == RequestParameter.class) {
                FieldUtils.writeField(field, target, val, true);
            } else {
                try {
                    FieldUtils.writeField(field, target, ((RequestParameter) val).getInputStream(), true);
                } catch (IOException ex) {
                    LOG.error("Unable to get InputStream for uploaded file [ {} ]",
                            ((RequestParameter) val).getName(), ex);
                }
            }
        } else {
            parseInputValue(target, String.valueOf(val), field);
        }
    }
}

From source file:com.fengduo.bee.commons.core.lang.BeanUtils.java

/**
 * ?Beanmap,map/*from w  w w.  j a  v a  2 s. c  o  m*/
 * 
 * @param bean
 * @return
 */
public static Map<String, String> getFieldValueMap(Object bean) {
    Class<?> cls = bean.getClass();
    Map<String, String> valueMap = new LinkedHashMap<String, String>();
    LinkedList<Field> fields = _getAllFields(new LinkedList<Field>(), cls);

    for (Field field : fields) {
        try {
            if (field == null || field.getName() == null) {
                continue;
            }
            if (StringUtils.equals("serialVersionUID", field.getName())) {
                continue;
            }

            Object fieldVal = PropertyUtils.getProperty(bean, field.getName());

            String result = null;
            if (null != fieldVal) {
                if (StringUtils.equals("Date", field.getType().getSimpleName())) {
                    result = DateViewTools.formatFullDate((Date) fieldVal);
                } else {
                    result = String.valueOf(fieldVal);
                }
            }
            valueMap.put(field.getName(), result == null ? StringUtils.EMPTY : result);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            continue;
        }
    }
    return valueMap;
}

From source file:com.googlecode.dex2jar.test.TestUtils.java

public static byte[] testDexASMifier(Class<?> clz, String methodName, String generateClassName)
        throws Exception {
    final ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, generateClassName, null, "java/lang/Object", null);
    EmptyVisitor em = new EmptyVisitor() {
        public DexMethodVisitor visitMethod(int accessFlags, com.googlecode.dex2jar.Method method) {
            return new V3MethodAdapter(accessFlags, method, null,
                    V3.OPTIMIZE_SYNCHRONIZED | V3.TOPOLOGICAL_SORT) {
                @Override//from ww  w. j a v  a2  s  . com
                public void visitEnd() {
                    super.visitEnd();
                    methodNode.accept(cw);
                }
            };
        }

        @Override
        public DexFieldVisitor visitField(int accessFlags, com.googlecode.dex2jar.Field field, Object value) {
            FieldVisitor fv = cw.visitField(accessFlags, field.getName(), field.getType(), null, value);
            fv.visitEnd();
            return null;
        }
    };
    Method m = clz.getMethod(methodName, DexClassVisitor.class);
    if (m == null) {
        throw new java.lang.NoSuchMethodException(methodName);
    }
    m.setAccessible(true);
    m.invoke(null, em);
    byte[] data = cw.toByteArray();
    ClassReader cr = new ClassReader(data);
    TestUtils.verify(cr);
    return data;
}

From source file:com.vk.sdk.api.model.ParseUtils.java

/**
* Parses object with follow rules:/*  ww  w  .  j  av  a  2  s.  co  m*/
*
* 1. All fields should had a public access.
* 2. The name of the filed should be fully equal to name of JSONObject key.
* 3. Supports parse of all Java primitives, all {@link String},
* arrays of primitive types, {@link String}s and {@link com.vk.sdk.api.model.VKApiModel}s,
* list implementation line {@link com.vk.sdk.api.model.VKList}, {@link com.vk.sdk.api.model.VKAttachments.VKAttachment} or {@link com.vk.sdk.api.model.VKPhotoSizes},
* {@link com.vk.sdk.api.model.VKApiModel}s.
*
* 4. Boolean fields defines by vk_int == 1 expression.
* @param object object to initialize
* @param source data to read values
* @return initialized according with given data object
* @throws JSONException if source object structure is invalid
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <T> T parseViaReflection(T object, JSONObject source) throws JSONException {
    if (source.has("response")) {
        source = source.optJSONObject("response");
    }
    if (source == null) {
        return object;
    }
    for (Field field : object.getClass().getFields()) {
        field.setAccessible(true);
        String fieldName = field.getName();
        Class<?> fieldType = field.getType();

        Object value = source.opt(fieldName);
        if (value == null) {
            continue;
        }
        try {
            if (fieldType.isPrimitive() && value instanceof Number) {
                Number number = (Number) value;
                if (fieldType.equals(int.class)) {
                    field.setInt(object, number.intValue());
                } else if (fieldType.equals(long.class)) {
                    field.setLong(object, number.longValue());
                } else if (fieldType.equals(float.class)) {
                    field.setFloat(object, number.floatValue());
                } else if (fieldType.equals(double.class)) {
                    field.setDouble(object, number.doubleValue());
                } else if (fieldType.equals(boolean.class)) {
                    field.setBoolean(object, number.intValue() == 1);
                } else if (fieldType.equals(short.class)) {
                    field.setShort(object, number.shortValue());
                } else if (fieldType.equals(byte.class)) {
                    field.setByte(object, number.byteValue());
                }
            } else {
                Object result = field.get(object);
                if (value.getClass().equals(fieldType)) {
                    result = value;
                } else if (fieldType.isArray() && value instanceof JSONArray) {
                    result = parseArrayViaReflection((JSONArray) value, fieldType);
                } else if (VKPhotoSizes.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKAttachments.class.isAssignableFrom(fieldType) && value instanceof JSONArray) {
                    Constructor<?> constructor = fieldType.getConstructor(JSONArray.class);
                    result = constructor.newInstance((JSONArray) value);
                } else if (VKList.class.equals(fieldType)) {
                    ParameterizedType genericTypes = (ParameterizedType) field.getGenericType();
                    Class<?> genericType = (Class<?>) genericTypes.getActualTypeArguments()[0];
                    if (VKApiModel.class.isAssignableFrom(genericType)
                            && Parcelable.class.isAssignableFrom(genericType)
                            && Identifiable.class.isAssignableFrom(genericType)) {
                        if (value instanceof JSONArray) {
                            result = new VKList((JSONArray) value, genericType);
                        } else if (value instanceof JSONObject) {
                            result = new VKList((JSONObject) value, genericType);
                        }
                    }
                } else if (VKApiModel.class.isAssignableFrom(fieldType) && value instanceof JSONObject) {
                    result = ((VKApiModel) fieldType.newInstance()).parse((JSONObject) value);
                }
                field.set(object, result);
            }
        } catch (InstantiationException e) {
            throw new JSONException(e.getMessage());
        } catch (IllegalAccessException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodException e) {
            throw new JSONException(e.getMessage());
        } catch (InvocationTargetException e) {
            throw new JSONException(e.getMessage());
        } catch (NoSuchMethodError e) {
            // ?????????? ???????:
            // ?? ?? ????????, ?? ? ????????? ???????? getFields() ???????? ??? ???.
            // ?????? ? ??????? ???????????, ????????? ?? ? ????????, ?????? Android ? ???????? ????????? ??????????.
            throw new JSONException(e.getMessage());
        }
    }
    return object;
}

From source file:edu.wright.daselab.linkgen.ConfigurationParams.java

public final static boolean checkStatusOnLoad() throws Exception {
    // using reflection to check all properties/params fields.
    // you can use annotation for better retrieval
    // http://stackoverflow.com/questions/2020202/pitfalls-in-getting-member-variable-values-in-java-with-reflection
    // by this time, none of the values are empty.
    String name = "";
    String value = "";
    logger.info("Displaying all param values:");
    boolean isFine = true;
    Field[] fields = ConfigurationParams.class.getDeclaredFields();
    for (Field field : fields) {
        // check only final static fields
        if (!Modifier.isFinal((field.getModifiers())) || (!Modifier.isStatic(field.getModifiers()))) {
            continue;
        }// w  w  w  .  ja  va  2  s.  c o  m
        name = field.getName();
        try {
            value = (String) field.get(null).toString();
        } catch (Exception e) {
            Monitor.error(Error.INVALID_CONFIG_PARAMS.toString());
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
        }
        if ((value == null) || value.toString().trim().equals("")) {
            isFine = false;
        }
        String status = isFine ? "OK" : "Failed";
        logger.info(status + " \t" + name + "=" + value);
        if (!isFine)
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
    }
    return isFine;
}

From source file:com.google.gdt.eclipse.designer.ie.util.ReflectionUtils.java

/**
 * @return the {@link Field} of given class with given name or <code>null</code> if no such {@link Field}
 *         found.// w w w . j  a  v a2  s.  c  o  m
 */
public static Field getFieldByName(Class<?> clazz, String name) {
    Assert.isNotNull(clazz);
    Assert.isNotNull(name);
    // check fields of given class and its super classes
    while (clazz != null) {
        // check all declared field
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field field : declaredFields) {
            if (field.getName().equals(name)) {
                field.setAccessible(true);
                return field;
            }
        }
        // check interfaces
        {
            Class<?>[] interfaceClasses = clazz.getInterfaces();
            for (Class<?> interfaceClass : interfaceClasses) {
                Field field = getFieldByName(interfaceClass, name);
                if (field != null) {
                    return field;
                }
            }
        }
        // check superclass
        clazz = clazz.getSuperclass();
    }
    // not found
    return null;
}