Example usage for java.lang Class getDeclaredField

List of usage examples for java.lang Class getDeclaredField

Introduction

In this page you can find the example usage for java.lang Class getDeclaredField.

Prototype

@CallerSensitive
public Field getDeclaredField(String name) throws NoSuchFieldException, SecurityException 

Source Link

Document

Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.

Usage

From source file:gemlite.core.internal.measurement.index.BigComparator.java

private Map<String, String> getKeyFields() {
    if (keyFields == null) {
        keyFields = new HashMap<>();
        try {// www .jav a  2 s  .  c  om
            GemliteIndexContext idc = GemliteContext.getTopIndexContext();
            IIndexContext context = idc.getIndexContext(indexName);
            if (context != null) {
                IndexTool indexTool = (IndexTool) context.getIndexInstance();
                Set idxKeyFields = indexTool.getKeyFieldNames();
                IMapperTool mapperTool = DomainRegistry.getMapperTool(regionName);
                Class valueClass = mapperTool.getValueClass();
                for (Iterator it2 = idxKeyFields.iterator(); it2.hasNext();) {
                    String idxField = (String) it2.next();
                    Field field = valueClass.getDeclaredField(idxField);
                    String type = field.getType().getSimpleName();
                    keyFields.put(idxField, type);
                }
            }
        } catch (Exception e) {
            LogUtil.getCoreLog().error("Get Index Key Info error.", e);
        }
    }
    return keyFields;
}

From source file:com.datatorrent.contrib.enrichment.POJOEnrichmentOperator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Getter generateGettersForField(Class<?> klass, String inputFieldName)
        throws NoSuchFieldException, SecurityException {
    Field f = klass.getDeclaredField(inputFieldName);
    Class c = ClassUtils.primitiveToWrapper(f.getType());
    Getter classGetter = PojoUtils.createGetter(klass, inputFieldName, c);
    return classGetter;
}

From source file:info.guardianproject.netcipher.web.WebkitProxy.java

/**
 * Set Proxy for Android 3.2 and below./*from w w  w. j a va  2s. c om*/
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private QName findFieldElementQNameUncached(String fieldName, Class beanClass, String defaultNamespace) {
    Field field;/*w w  w.jav  a 2s.  co  m*/
    try {
        field = beanClass.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        return new QName(defaultNamespace, fieldName); // TODO implement this if needed (lookup the getter method instead of the field)
    }
    String realLocalName = fieldName;
    String realNamespace = defaultNamespace;
    XmlElement xmlElement = field.getAnnotation(XmlElement.class);
    if (xmlElement != null) {
        String name = xmlElement.name();
        if (!BeanMarshaller.DEFAULT_PLACEHOLDER.equals(name)) {
            realLocalName = name;
        }
        String namespace = xmlElement.namespace();
        if (!BeanMarshaller.DEFAULT_PLACEHOLDER.equals(namespace)) {
            realNamespace = namespace;
        }
    }
    return new QName(realNamespace, realLocalName);
}

From source file:com.medsphere.fileman.FMRecord.java

protected void setDomainValue(String fieldName, Object value) {
    try {/*from   w  ww. j  a  v  a2s . c  o  m*/
        Class thisClass = getClass();

        Field field = null;
        Class curClass = thisClass;
        while (!curClass.equals(FMRecord.class)) {
            try {
                field = curClass.getDeclaredField(fieldName);
                String number = field.getAnnotation(FMAnnotateFieldInfo.class).number();
                setDomainValue(fieldName, value, number);
                break;
            } catch (NoSuchFieldException e) {
            }
            curClass = curClass.getSuperclass();

        }

        if (field == null)

            throw new NoSuchFieldException();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:net.nan21.dnet.core.presenter.service.ds.AbstractEntityDsWriteService.java

protected void doImportAsUpdate_(File file, String ukFieldName, int batchSize, Object config) throws Exception {
    if (this.isReadOnly()) {
        throw new ActionNotSupportedException("Import not allowed.");
    }//from  w w  w .  j a v a 2s . c  o  m
    Assert.notNull(ukFieldName, "For import as update you must specify the unique-key "
            + "field which is used to lookup the existing record.");

    // TODO: check type-> csv, json, etc
    DsCsvLoader l = new DsCsvLoader();
    if (config != null && config instanceof ConfigCsvImport) {
        l.setConfig((ConfigCsvImport) config);
    }
    DsCsvLoaderResult<M> result = l.run2(file, this.getModelClass(), null);
    List<M> list = result.getResult();
    String[] columns = result.getHeader();

    F filter = this.getFilterClass().newInstance();

    // TODO: optimize me to do the work in batches

    Method filterUkFieldSetter = this.getFilterClass().getMethod("set" + StringUtils.capitalize(ukFieldName),
            String.class);
    Method modelUkFieldGetter = this.getModelClass().getMethod("get" + StringUtils.capitalize(ukFieldName));

    Map<String, Method> modelSetters = new HashMap<String, Method>();
    Map<String, Method> modelGetters = new HashMap<String, Method>();

    int len = columns.length;

    for (int i = 0; i < len; i++) {
        String fieldName = columns[i];
        Class<?> clz = this.getModelClass();
        Field f = null;
        while (f == null && clz != null) {
            try {
                f = clz.getDeclaredField(fieldName);
            } catch (Exception e) {

            }
            clz = clz.getSuperclass();
        }

        if (f != null) {
            Method modelSetter = this.getModelClass().getMethod("set" + StringUtils.capitalize(fieldName),
                    f.getType());
            modelSetters.put(fieldName, modelSetter);

            Method modelGetter = this.getModelClass().getMethod("get" + StringUtils.capitalize(fieldName));
            modelGetters.put(fieldName, modelGetter);
        } else {

        }
    }

    List<M> targets = new ArrayList<M>();

    for (M newDs : list) {
        filterUkFieldSetter.invoke(filter, modelUkFieldGetter.invoke(newDs));
        List<M> res = this.find(filter);
        // TODO: add an extra flag for what to do if the target is not
        // found:
        // ignore or raise an error
        if (res.size() > 0) {
            M oldDs = this.find(filter).get(0);
            for (Map.Entry<String, Method> entry : modelSetters.entrySet()) {
                entry.getValue().invoke(oldDs, modelGetters.get(entry.getKey()).invoke(newDs));
            }
            targets.add(oldDs);
            // this.update(oldDs, null);
        }
    }

    this.update(targets, null);
    try {
        this.getEntityService().getEntityManager().flush();
    } catch (Exception e) {

    }
}

From source file:jenkins.plugins.shiningpanda.ShiningPandaTestCase.java

/**
 * Search a field in the provided class and its super classes.
 * //from ww  w  .ja v  a 2 s .  c o  m
 * @param klass
 *            The class to search in.
 * @param p
 *            The field to search.
 * @return The field, or null if no such field.
 */
protected Field getField(@SuppressWarnings("rawtypes") Class klass, String p) {
    while (klass != Object.class) {
        try {
            return klass.getDeclaredField(p);
        } catch (NoSuchFieldException e) {
        }
        klass = klass.getSuperclass();
    }
    return null;
}

From source file:com.medsphere.fileman.FMRecord.java

protected void setDomainValue(String fieldName, Object value, String number) {
    boolean didFieldSet = false;
    try {/*from ww  w  .  jav a 2  s .  c  o m*/
        Class thisClass = getClass();
        Field field = null;
        Class curClass = thisClass;
        while (!curClass.equals(FMRecord.class)) {
            try {
                field = curClass.getDeclaredField(fieldName);
                break;
            } catch (NoSuchFieldException e) {
            }
            curClass = curClass.getSuperclass();

        }

        if (field != null) {
            field.setAccessible(true);
            Object currentValue = field.get(this);
            if (valuesChanged(currentValue, value)) {
                field.set(this, value);
                addModifiedField(number);
            }
            didFieldSet = true;
        } else
            throw new NoSuchFieldException();
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    if (!didFieldSet) {
        acceptField(fieldName, value.toString());
    }
}

From source file:com.haulmont.cuba.core.app.serialization.EntitySerialization.java

@Nullable
protected Field getField(@Nullable Class clazz, String fieldName) {
    try {/*from  ww  w  . j  ava2s. c om*/
        if (clazz != null) {
            return clazz.getDeclaredField(fieldName);
        }
    } catch (NoSuchFieldException ex) {
        return getField(clazz.getSuperclass(), fieldName);
    }
    return null;
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private QName findFieldElementQNameUncached(String fieldName, Class beanClass, String defaultNamespace) {
    Field field;/*from  www  .  j a va  2  s  .c  o m*/
    try {
        field = beanClass.getDeclaredField(fieldName);
    } catch (NoSuchFieldException e) {
        return new QName(defaultNamespace, fieldName); // TODO implement this if needed (lookup the getter method instead of the field)
    }
    String realLocalName = fieldName;
    String realNamespace = defaultNamespace;
    XmlElement xmlElement = field.getAnnotation(XmlElement.class);
    if (xmlElement != null) {
        String name = xmlElement.name();
        if (name != null && !PrismBeanConverter.DEFAULT_PLACEHOLDER.equals(name)) {
            realLocalName = name;
        }
        String namespace = xmlElement.namespace();
        if (namespace != null && !PrismBeanConverter.DEFAULT_PLACEHOLDER.equals(namespace)) {
            realNamespace = namespace;
        }
    }
    return new QName(realNamespace, realLocalName);
}