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:gr.abiss.calipso.jpasearch.specifications.GenericSpecifications.java

public static Field getField(Class<?> clazz, String fieldName) {
    Field field = null;/*from  w w w.  j  a va  2s. co m*/
    if (!IGNORED_FIELD_NAMES.contains(fieldName)) {

        String key = clazz.getName() + "#" + fieldName;
        field = FIELD_CACHE.get(key);

        // find it if not cached
        if (field == null && !FIELD_CACHE.containsKey(key)) {
            Class<?> tmpClass = clazz;
            do {
                for (Field tmpField : tmpClass.getDeclaredFields()) {
                    String candidateName = tmpField.getName();
                    if (candidateName.equals(fieldName)) {
                        // field.setAccessible(true);
                        FIELD_CACHE.put(key, tmpField);
                        field = tmpField;
                        break;
                    }
                }
                tmpClass = tmpClass.getSuperclass();
            } while (tmpClass != null && field == null);
        }
        if (field == null) {
            LOGGER.warn("Field '" + fieldName + "' not found on class " + clazz);
            // HashMap handles null values so we can use containsKey to cach
            // invalid fields and hence skip the reflection scan
            FIELD_CACHE.put(key, null);
        }
        // throw new RuntimeException("Field '" + fieldName +
        // "' not found on class " + clazz);
    }

    return field;
}

From source file:Main.java

/**
 * Check application's R.id class and retrieve the value of the static
 * member with the given name.//w w w.  j a  v a 2 s  . c om
 */
public static int getIdentifierFromR(Context context, String type, String name) {
    Class<?> rClass = null;
    try {
        rClass = Class.forName(context.getPackageName() + ".R$" + type);
    } catch (ClassNotFoundException e) {
        // No R.id class? This should never happen.
        throw new RuntimeException(e);
    }

    try {
        Field rField = rClass.getField(name);
        Object intValue;
        try {
            intValue = rField.get(null);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        if (!(intValue instanceof Integer)) {
            throw new RuntimeException("Not an int: " + rClass.getCanonicalName() + "." + rField.getName());
        }
        return ((Integer) intValue).intValue();
    } catch (NoSuchFieldException e) {
        throw new RuntimeException("There is no such id in the R class: " + context.getPackageName() + ".R."
                + type + "." + name + ")");
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jilk.ros.rosbridge.implementation.JSON.java

private static Message convertJSONObjectToMessage(JSONObject jo, Class c, Registry<Class> r) {
    //System.out.println("JSON.convertJSONObjectToMessage: " + jo.toJSONString());
    try {//from   w  ww .  java2  s  .  c  om
        Message result = (Message) c.newInstance();
        for (Field f : c.getFields()) {
            Class fc = getFieldClass(result, jo, f, r);
            Object lookup = jo.get(f.getName());
            if (lookup != null) {
                Object value = convertElementToField(lookup, fc, f, r);
                f.set(result, value);
            }
        }
        return result;
    } catch (Exception ex) {
        //ex.printStackTrace();
        return null;
    }
}

From source file:com.yukthi.utils.beans.PropertyMapper.java

/**
 * Checks in the cache if the specified bean type property details is already loaded. If loaded returns the same. If not, builds the property map
 * caches it and returns it.//from ww w . ja v a 2s .  c  om
 * @param beanType Bean types for which property map needs to be fetched
 * @return Property details of specified bean type
 */
public static synchronized BeanInfo getBeanInfo(Class<?> beanType) {
    BeanInfo beanInfo = typeToProp.get(beanType);

    //if type is already loaded return the same
    if (beanInfo != null) {
        return beanInfo;
    }

    beanInfo = new BeanInfo(beanType);
    Field fields[] = null;
    NestedProperty nestedProp = null;
    IgnorePropertyDestination ignorePropertyDestination = null;

    while (!beanType.getName().startsWith("java")) {
        fields = beanType.getDeclaredFields();

        //loop through property descriptors and add to bean property map
        for (Field field : fields) {
            try {
                nestedProp = NestedProperty.getNestedProperty(beanType, field.getName());
            } catch (Exception ex) {
                logger.info("Ignoring {}.{} property, as property fetch resulted in error - {}",
                        beanType.getName(), field.getName(), ex);
                continue;
            }

            ignorePropertyDestination = field.getAnnotation(IgnorePropertyDestination.class);

            beanInfo.addProperty(new PropertyInfo(nestedProp, ignorePropertyDestination != null));

            getMappingsFromField(beanInfo, field);
        }

        beanType = beanType.getSuperclass();
    }

    //cache and return property map
    typeToProp.put(beanType, beanInfo);
    return beanInfo;
}

From source file:com.mmj.app.lucene.solr.client.SolrClient.java

public static Object toBean(SolrDocument record, Class<?> clazz) {

    Object o = null;/* w ww  . j a v a 2  s  .c  o m*/
    try {
        o = clazz.newInstance();
    } catch (InstantiationException e1) {
        e1.printStackTrace();
    } catch (IllegalAccessException e1) {
        e1.printStackTrace();
    }
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        Object value = record.get(field.getName());
        ConvertUtils.register(new DateConverter(null), java.util.Date.class);
        try {
            BeanUtils.setProperty(o, field.getName(), value);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    return o;
}

From source file:eu.udig.omsbox.utils.OmsBoxUtils.java

private static void collectParameters(StringBuilder sbTmp, Collection<Access> accessList) throws Exception {
    for (Access access : accessList) {
        Field field = access.getField();
        String fieldName = field.getName();
        Description descriptionAnnot = field.getAnnotation(Description.class);

        if (fieldName.equals("pm")) {
            // ignore progress monitor
            continue;
        }/*  ww w . ja v a  2 s .co m*/
        String fieldDescription = " - ";
        if (descriptionAnnot != null) {
            fieldDescription = AnnotationUtilities.getLocalizedDescription(descriptionAnnot);
            if (fieldDescription == null) {
                fieldDescription = " - ";
            }

            Unit unitAnn = field.getAnnotation(Unit.class);
            if (unitAnn != null) {
                fieldDescription = fieldDescription + " [" + unitAnn.value() + "]";
            }
        }

        sbTmp.append("<tr>").append(NEWLINE);
        sbTmp.append("<td width=\"40%\"> <b>").append(fieldName).append("</b> </td><td width=\"60%\"> ");
        sbTmp.append(fieldDescription).append(" </td>").append(NEWLINE);
        sbTmp.append("</tr>").append(NEWLINE);
    }
}

From source file:com.taobao.adfs.database.tdhsocket.client.protocol.TDHSProtocolBinary.java

private static void encodeRequest(Request o, ByteArrayOutputStream out, String charestName)
        throws IllegalAccessException, IOException, TDHSEncodeException {
    for (Field f : o.getClass().getDeclaredFields()) {
        if (!Modifier.isPublic(f.getModifiers())) {
            f.setAccessible(true);//from w w w.j  av a2  s.  co  m
        }
        Object v = f.get(o);
        if (v instanceof Request) {
            encodeRequest((Request) v, out, charestName);
        } else if (f.getName().startsWith("_")) {
            writeObjectToStream(v, out, f.getName(), charestName);
        }
    }
}

From source file:net.ostis.sc.memory.SCKeynodesBase.java

private static boolean checkKeynodesNumberPatternURI(SCSession session, Class<?> klass, Field field)
        throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
    KeynodesNumberPatternURI patternURI = field.getAnnotation(KeynodesNumberPatternURI.class);

    if (patternURI != null) {
        String[] comp = URIUtils.splitByIdtf(patternURI.patternURI());

        SCSegment segment = session.openSegment(comp[0]);

        List<SCAddr> keynodes = new LinkedList<SCAddr>();
        for (int i = patternURI.startIndex(); i <= patternURI.endIndex(); ++i) {
            String keynodeName = MessageFormat.format(comp[1], i);

            SCAddr keynode = session.findByIdtf(keynodeName, segment);
            Validate.notNull(keynode, keynodeName);

            keynodes.add(keynode);//w w  w. j  ava 2s .  c o m

            String fieldName = MessageFormat.format(patternURI.patternName(), i);
            Field keynodeField = klass.getField(fieldName);
            keynodeField.set(null, keynode);

            if (log.isDebugEnabled())
                log.debug(comp[0] + "/" + keynodeName + " --> " + keynodeField.getName());
        }

        field.set(null, (SCAddr[]) keynodes.toArray(new SCAddr[keynodes.size()]));

        if (log.isDebugEnabled())
            log.debug(patternURI.patternURI() + " --> " + field.getName());

        return true;
    } else {
        return false;
    }
}

From source file:com.ocs.dynamo.test.MockUtil.java

/**
 * Registers all fields that are annotated with "@Mock" as beans in the Spring context
 * //  w ww  .  j a  v  a 2 s. co m
 * @param factory
 * @param subject
 * @param clazz
 */
public static void registerMocks(ConfigurableListableBeanFactory factory, Object subject, Class<?> clazz) {
    try {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            if (field.getAnnotation(Mock.class) != null) {
                factory.registerSingleton(field.getName(), field.get(subject));
            }
        }
        if (clazz.getSuperclass() != null) {
            registerMocks(factory, subject, clazz.getSuperclass());
        }
    } catch (Exception e) {
        throw new OCSRuntimeException(e.getMessage(), e);
    }
}

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

public static void deserializeFields(Object target, List<Field> fields, ValueMap input)
        throws DeserializeException {
    for (Field field : fields) {
        try {/*from   w  ww . j  a  v a  2  s.co  m*/
            parseInput(target, input, field);
        } catch (ParseException | ReflectiveOperationException | NullPointerException ex) {
            throw new DeserializeException("Error when processing field " + field.getName(), ex);
        }
    }
}