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:com.lonepulse.robozombie.proxy.Zombie.java

/**
 * <p>Accepts an object and scans it for {@link Bite} annotations. If found, a <b>thread-safe proxy</b> 
 * for the endpoint interface will be injected.</p>
 * /*www.j  a  va 2 s . com*/
 * <p>Injection targets will be searched up an inheritance hierarchy until a type is found which is 
 * <b>not</b> in a package whose name starts with the given package prefixes.</p>
 * <br>
 * <b>Usage:</b>
 * <br><br>
 * <ul>
 * <li>
 * <h5>Property Injection</h5>
 * <pre>
 * <code><b>@Bite</b>
 * private GitHubEndpoint gitHubEndpoint;
 * {
 * &nbsp; &nbsp; Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this);
 * }
 * </code>
 * </pre>
 * </li>
 * <li>
 * <h5>Setter Injection</h5>
 * <pre>
 * <code><b>@Bite</b>
 * private GitHubEndpoint gitHubEndpoint;
 * {
 * &nbsp; &nbsp; Zombie.infect(Arrays.asList("com.example.service", "com.example.manager"), this);
 * }
 * </code>
 * <code>
 * public void setGitHubEndpoint(GitHubEndpoint gitHubEndpoint) {
 * 
 * &nbsp; &nbsp; this.gitHubEndpoint = gitHubEndpoint;
 * }
 * </code>
 * </pre>
 * </li>
 * </ul>
 * 
 * @param packagePrefixes
 *          the prefixes of packages to restrict hierarchical lookup of injection targets; if {@code null} 
 *          or {@code empty}, {@link #infect(Object, Object...)} will be used
 * <br><br>
 * @param victim
 *          an object with endpoint references marked to be <i>bitten</i> and infected 
 * <br><br>
 * @param moreVictims
 *          more unsuspecting objects with endpoint references to be infected
 * <br><br>
 * @throws NullPointerException
 *          if the object supplied for endpoint injection is {@code null} 
 * <br><br>
 * @since 1.3.0
 */
public static void infect(List<String> packagePrefixes, Object victim, Object... moreVictims) {

    assertNotNull(victim);

    List<Object> injectees = new ArrayList<Object>();
    injectees.add(victim);

    if (moreVictims != null && moreVictims.length > 0) {

        injectees.addAll(Arrays.asList(moreVictims));
    }

    Class<?> endpointInterface = null;

    for (Object injectee : injectees) {

        Class<?> type = injectee.getClass();

        do {

            for (Field field : Fields.in(type).annotatedWith(Bite.class)) {

                try {

                    endpointInterface = field.getType();
                    Object proxyInstance = EndpointProxyFactory.INSTANCE.create(endpointInterface);

                    try { //1.Simple Field Injection 

                        field.set(injectee, proxyInstance);
                    } catch (IllegalAccessException iae) { //2.Setter Injection 

                        String fieldName = field.getName();
                        String mutatorName = "set" + Character.toUpperCase(fieldName.charAt(0))
                                + fieldName.substring(1);

                        try {

                            Method mutator = injectee.getClass().getDeclaredMethod(mutatorName,
                                    endpointInterface);
                            mutator.invoke(injectee, proxyInstance);
                        } catch (NoSuchMethodException nsme) { //3.Forced Field Injection

                            field.setAccessible(true);
                            field.set(injectee, proxyInstance);
                        }
                    }
                } catch (Exception e) {

                    Log.e(Zombie.class.getName(),
                            new StringBuilder().append("Failed to inject the endpoint proxy instance of type ")
                                    .append(endpointInterface.getName()).append(" on property ")
                                    .append(field.getName()).append(" at ")
                                    .append(injectee.getClass().getName()).append(". ").toString(),
                            e);
                }
            }

            type = type.getSuperclass();
        } while (!hierarchyTerminal(type, packagePrefixes));
    }
}

From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java

/**
 * Initialize schema property names./*from   w w  w . ja v  a  2  s.c  o m*/
 */
public static void initializeSchemaPropertyNames() {
    synchronized (lockObject) {
        for (Class<?> type : ServiceObjectSchema.allSchemaTypes.getMember()) {
            Field[] fields = type.getDeclaredFields();
            for (Field field : fields) {
                int modifier = field.getModifiers();
                if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) {
                    Object o;
                    try {
                        o = field.get(null);
                        if (o instanceof PropertyDefinition) {
                            PropertyDefinition propertyDefinition = (PropertyDefinition) o;
                            propertyDefinition.setName(field.getName());
                        }
                    } catch (IllegalArgumentException e) {
                        LOG.error(e);

                        // Skip the field
                    } catch (IllegalAccessException e) {
                        LOG.error(e);

                        // Skip the field
                    }
                }
            }
        }
    }
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * @param primaryKeyField/*from ww  w. j av  a 2  s.c om*/
 * @return the column mapping to the {@link java.reflect.Field} annotated
 * with {@link javax.persistence.Id} and {@link javax.persistence.Column}
 *
 * @see http://docs.oracle.com/javaee/6/api/index.html?javax/persistence/Id.html
 */
public static String getPrimaryKeyColumnName(Field primaryKeyField) {
    Preconditions.checkNotNull(primaryKeyField);
    javax.persistence.Column column = primaryKeyField.getAnnotation(javax.persistence.Column.class);
    if (column == null) {
        /*
         * The documentation for @Id states that <quote>If no Column
         * annotation is specified, the primary key column name is assumed
         * to be the name of the primary key property or field.</quote>
         */
        return primaryKeyField.getName();
    } else {
        return normalizeCqlElementName(column.name());
    }
}

From source file:com.github.dactiv.common.utils.ReflectionUtils.java

/**
 * //from   w  ww . j  av  a2 s  .c  om
 * ?o??
 * 
 * @param targetClass
 *            Class
 * @param type
 *            ????
 * 
 * @return List
 */
public static List<String> getAccessibleFieldNames(final Class targetClass, Class type) {

    Assert.notNull(targetClass, "targetClass?");
    Assert.notNull(type, "type?");

    List<String> list = new ArrayList<String>();

    for (Field field : targetClass.getDeclaredFields()) {
        if (field.getType().equals(type)) {
            list.add(field.getName());
        }
    }

    return list;
}

From source file:org.fusesource.meshkeeper.util.internal.IntrospectionSupport.java

private static void addFields(Object target, Class<?> startClass, Class<?> stopClass,
        LinkedHashMap<String, Object> map) {

    if (startClass != stopClass) {
        addFields(target, startClass.getSuperclass(), stopClass, map);
    }/* www .  j  ava2s .  c om*/

    Field[] fields = startClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())
                || Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        try {
            field.setAccessible(true);
            Object o = field.get(target);
            if (o != null && o.getClass().isArray()) {
                try {
                    o = Arrays.asList((Object[]) o);
                } catch (Throwable e) {
                }
            }
            map.put(field.getName(), o);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

}

From source file:Main.java

public static <T> ArrayList<HashMap<String, String>> prepareDataToSave(

        ArrayList<T> source, Class<T> classType)
        throws NoSuchMethodException, SecurityException, IllegalArgumentException, IllegalAccessException {

    ArrayList<HashMap<String, String>> destination = new ArrayList<HashMap<String, String>>();
    ArrayList<Field> savedFieds = new ArrayList<Field>();
    Field[] fields;//from   ww w . j a  va2s .  c o m
    Object value = null;
    HashMap<String, String> aux;
    Field auxField;

    fields = classType.getDeclaredFields();

    for (int j = 0; j < fields.length; j++) {

        Class<?> type = fields[j].getType();

        if (!(Modifier.isStatic(fields[j].getModifiers()) || Modifier.isFinal(fields[j].getModifiers())
                || type.isArray() || Collection.class.isAssignableFrom(type))) {

            savedFieds.add(fields[j]);

        }
    }

    if (classType == null || fields == null) {
        return null;
    }

    for (int i = 0; i < source.size(); i++) {
        aux = new HashMap<String, String>();

        for (int j = 0; j < savedFieds.size(); j++) {

            auxField = savedFieds.get(j);
            auxField.setAccessible(true);
            value = auxField.get(source.get(i));
            aux.put(auxField.getName(), value.toString());

        }

        destination.add(aux);
    }

    return destination;

}

From source file:adalid.core.XS1.java

static void logFieldAnnotationErrorMessage(Field field, Class<?> annotation, String string) {
    String name = field.getName();
    Class<?> type = field.getDeclaringClass();
    logFieldAnnotationErrorMessage(name, type, annotation, string);
}

From source file:com.diversityarrays.kdxplore.importdata.bms.BmsExcelImportHelper.java

static public Map<String, Field> getFieldByFactorName(ExportOptions options) {

    Collection<Field> plotFields = PLOT_FIELD_BY_FACTOR_NAME.values();

    Map<String, Field> fieldNameByName = new HashMap<>();
    for (Field field : plotFields) {
        fieldNameByName.put(field.getName(), field);
    }//  w  w w  .  jav  a  2 s.c om

    Map<String, Field> fieldByFactorName = new TreeMap<>();

    for (String fieldName : fieldNameByName.keySet()) {
        Field field = fieldNameByName.get(fieldName);
        if (Plot.FIELDNAME_PLOT_TYPE.equals(fieldName)) {
            fieldByFactorName.put(BmsConstant.XLSHDG_ENTRY_TYPE, field);
        } else if (Plot.FIELDNAME_USER_PLOT_ID.equals(fieldName)) {
            fieldByFactorName.put(BmsConstant.XLSHDG_PLOT_NO, field);
        } else if (Plot.FIELDNAME_PLOT_ROW.equals(fieldName)) {
            String name = options.nameForRow;
            if (Check.isEmpty(name)) {
                name = BmsConstant.XLSHDG_FIELDMAP_RANGE;
            }
            fieldByFactorName.put(name, field);
        } else if (Plot.FIELDNAME_PLOT_COLUMN.equals(fieldName)) {
            String name = options.nameForColumn;
            if (Check.isEmpty(name)) {
                name = BmsConstant.XLSHDG_FIELDMAP_COLUMN;
            }
            fieldByFactorName.put(name, field);
        } else {
            // TODO error
        }
    }

    return fieldByFactorName;
}

From source file:com.aw.swing.mvp.view.IPView.java

public static List<JComponent> getCmps(Object target) {
    //        logger.info("searching attributes " + target.getClass().getName());
    List components = new ArrayList();
    List<Field> forms = new ArrayList();
    Class cls = target.getClass();
    Field[] fields = cls.getFields();
    for (int i = 0; i < fields.length; i++) {
        if ((fields[i].getName().startsWith("txt") || fields[i].getName().startsWith("chk"))
                && !fields[i].getName().startsWith("chkSel")) {
            JComponent jComponemt;
            try {
                jComponemt = (JComponent) fields[i].get(target);
                if (jComponemt != null) {
                    jComponemt.putClientProperty("Field", fields[i]);
                    components.add(jComponemt);
                } else {
                    System.out.println("Null:<" + target.getClass() + ">- <" + fields[i].getName() + ">");
                }/*  w  w  w  .jav a 2  s  .c o  m*/
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new AWSystemException("Error getting teh value of:<" + fields[i].getName() + ">", e);
            }
        }
        if ((fields[i].getType().getSimpleName().startsWith("Frm"))) {
            forms.add(fields[i]);
        }
    }
    if (forms.size() > 0) {
        for (Field field : forms) {
            try {
                Object formToBeChecked = field.get(target);
                if (formToBeChecked != null) {
                    List formAttributes = getCmps(formToBeChecked);
                    if (formAttributes.size() > 0) {
                        components.addAll(formAttributes);
                    }
                } else {
                    throw new IllegalStateException("FRM NULL:" + field.getName());
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                throw new AWSystemException("Problems getting value for:<" + field.getName() + ">", e);
            }
        }
    }
    return components;
}

From source file:org.cybercat.automation.annotations.AnnotationBuilder.java

/**
 * @param targetObject//from w  w  w  . j  ava2  s .c  om
 * @param fields
 * @param i
 * @throws AutomationFrameworkException
 */
public static void processPropertyField(Object targetObject, Field field) throws AutomationFrameworkException {
    try {
        CCProperty properties = field.getAnnotation(CCProperty.class);
        StringBuffer value = new StringBuffer("");
        for (String prop : properties.value()) {
            value.append(AutomationMain.getProperty(prop));
        }
        field.set(targetObject, value.toString());
    } catch (Exception e) {
        throw new AutomationFrameworkException(
                "Set filed exception. Please, save this log and contact the Cybercat project support."
                        + " field name: " + field.getName() + " class: "
                        + targetObject.getClass().getSimpleName() + " Thread ID:"
                        + Thread.currentThread().getId(),
                e);
    }
}