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:info.guardianproject.netcipher.webkit.WebkitProxy.java

@TargetApi(19)
private static boolean setKitKatProxy(String appClass, Context appContext, String host, int port) {
    //Context appContext = webView.getContext().getApplicationContext();

    if (host != null) {
        System.setProperty("http.proxyHost", host);
        System.setProperty("http.proxyPort", Integer.toString(port));
        System.setProperty("https.proxyHost", host);
        System.setProperty("https.proxyPort", Integer.toString(port));
    }//from  w  w  w.j  a  v a 2s .com

    try {
        Class applictionCls = Class.forName(appClass);
        Field loadedApkField = applictionCls.getField("mLoadedApk");
        loadedApkField.setAccessible(true);
        Object loadedApk = loadedApkField.get(appContext);
        Class loadedApkCls = Class.forName("android.app.LoadedApk");
        Field receiversField = loadedApkCls.getDeclaredField("mReceivers");
        receiversField.setAccessible(true);
        ArrayMap receivers = (ArrayMap) receiversField.get(loadedApk);
        for (Object receiverMap : receivers.values()) {
            for (Object rec : ((ArrayMap) receiverMap).keySet()) {
                Class clazz = rec.getClass();
                if (clazz.getName().contains("ProxyChangeListener")) {
                    Method onReceiveMethod = clazz.getDeclaredMethod("onReceive", Context.class, Intent.class);
                    Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);

                    if (host != null) {
                        /*********** optional, may be need in future *************/
                        final String CLASS_NAME = "android.net.ProxyProperties";
                        Class cls = Class.forName(CLASS_NAME);
                        Constructor constructor = cls.getConstructor(String.class, Integer.TYPE, String.class);
                        constructor.setAccessible(true);
                        Object proxyProperties = constructor.newInstance(host, port, null);
                        intent.putExtra("proxy", (Parcelable) proxyProperties);
                        /*********** optional, may be need in future *************/
                    }

                    onReceiveMethod.invoke(rec, appContext, intent);
                }
            }
        }
        return true;
    } catch (ClassNotFoundException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchFieldException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalAccessException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (IllegalArgumentException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (NoSuchMethodException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InvocationTargetException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    } catch (InstantiationException e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        String exceptionAsString = sw.toString();
        Log.v(TAG, e.getMessage());
        Log.v(TAG, exceptionAsString);
    }
    return false;
}

From source file:com.helpinput.utils.Utils.java

public static Field findField(Class<?> targetClass, String fieldName) {
    Field theField;//from   ww w .ja va  2  s.  c  o  m
    try {
        theField = targetClass.getDeclaredField(fieldName);
        return accessible(theField);
    } catch (NoSuchFieldException e) {
        if (targetClass.getSuperclass() != null)
            return findField(targetClass.getSuperclass(), fieldName);
        else
            return null;
    }
}

From source file:com.helpinput.core.Utils.java

public static Field findField(Object target, String fieldName) {
    Class<?> targetClass = getClass(target);
    Field theField;//  w  ww . j ava 2  s.  c o m
    try {
        theField = targetClass.getDeclaredField(fieldName);
        return setAccess(theField);
    } catch (NoSuchFieldException e) {
        if (targetClass.getSuperclass() != null)
            return findField(targetClass.getSuperclass(), fieldName);
        else
            return null;
    }
}

From source file:com.google.code.ddom.commons.cl.ClassLoaderLocal.java

private static Map<ClassLoaderLocal<?>, Object> getClassLoaderLocalMap(ClassLoader cl) {
    if (cl == ClassLoaderLocal.class.getClassLoader()) {
        return ClassLoaderLocalMapHolder.locals;
    } else {//  w  w w .  j a  v a  2 s . c o  m
        Class<?> holderClass;
        try {
            holderClass = cl.loadClass(holderClassName);
            if (holderClass.getClassLoader() != cl) {
                holderClass = null;
            }
        } catch (ClassNotFoundException ex) {
            holderClass = null;
        }
        if (holderClass == null) {
            try {
                holderClass = (Class<?>) defineClassMethod.invoke(cl, holderClassName, holderClassDef, 0,
                        holderClassDef.length);
            } catch (Exception ex) {
                // TODO: can we get here? maybe if two threads call getClassLoaderLocalMap concurrently?
                throw new Error(ex);
            }
        }
        Field field;
        try {
            field = holderClass.getDeclaredField("locals");
        } catch (NoSuchFieldException ex) {
            throw new NoSuchFieldError(ex.getMessage());
        }
        try {
            return (Map<ClassLoaderLocal<?>, Object>) field.get(0);
        } catch (IllegalAccessException ex) {
            throw new Error(ex);
        }
    }
}

From source file:org.newcashel.meta.model.NCClass.java

public static void load(HSSFWorkbook wb, LaunchParms launchParm) throws Exception {

    // load the sheet
    Sheet sheet = wb.getSheet("ClassAttributes");
    if (sheet == null) {
        throw new Exception("The ClassAttributes sheet was not found in the MetaBook, terminate load process");
    }//from w  w w .j  av a  2  s .  co m

    //String[] fieldNames = POIUtil.getFirstRowVals(sheet);

    Class cls = Class.forName("org.newcashel.meta.model.NCClass");
    Class[] parmString = new Class[1];

    Row row = null;

    try {

        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            // skip blank rows between class attributes
            row = sheet.getRow(i);

            if (row != null && (POIUtil.getCellValue(row, ATTRIBUTE_OFFSET) == null
                    || POIUtil.getCellValue(row, TYPE_OFFSET).length() < 1))
                continue;

            // get the size of the cell, the length will be the number of atbs in the class
            // determine if the next Cell to the left is a separate Cell or part of a CellRangeAddress
            Cell cell = row.getCell(0, Row.RETURN_BLANK_AS_NULL);
            if (cell == null) {
                continue;
            }

            CellRangeAddress cra = getCellRangeAddress(sheet, row.getRowNum(), 0);
            if (cra == null) {
                return;
            }

            // instantiate the NCClass instance
            NCClass ncClass = new NCClass();
            ncClass.setClassName(POIUtil.getCellValue(row, CLASSNAME_OFFSET));
            //logger.info("loading NCClass " + ncClass.getClassName());

            ncClass.setSuperClassName(POIUtil.getCellValue(row, SUPERCLASS_NAME_OFFSET));
            ncClass.setClassParent(POIUtil.getCellValue(row, PARENTCLASS_OFFSET));
            ncClass.setPrimaryKey(POIUtil.getCellValue(row, PRIMARYKEY_OFFSET));
            ncClass.setPercolate(new Boolean(POIUtil.getCellValue(row, PERCOLATE_OFFSET)));
            ncClass.setGroupConstrain(new Boolean(POIUtil.getCellValue(row, GROUP_CONSTRAIN_OFFSET)));

            // not throwing java class errors, may not be significant to load context

            // TODO, if NO_VERIFY_JAVA_CLASS is true, skip validation
            // TODO, if NO_VERF true and blank 

            String javaClassName = POIUtil.getCellValue(row, JAVA_CLASS_OFFSET);
            if (javaClassName.endsWith("Person.class")) {
                System.out.println("OKK");
            }
            Class<?> javaCls = null;
            if (javaClassName != null && javaClassName.length() > 0) {
                ncClass.setJavaClassName(javaClassName);
                try {
                    javaCls = Class.forName(javaClassName);
                } catch (Exception e) {
                    logger.error("Java class specified but cannot be loaded for " + ncClass.getClassName()
                            + ", " + javaClassName);
                }
            } else {
                logger.info("no java class specified for class " + ncClass.getClassName());
            }

            classes.put(ncClass.getClassName(), ncClass);
            logger.info("Adding class " + ncClass.getClassName());

            // loop for all the rows in the cell range
            for (i = cra.getFirstRow(); i <= cra.getLastRow(); i++) {
                row = sheet.getRow(i);
                if (row == null) {
                    return; // range iteration complete
                }
                cell = row.getCell(ATTRIBUTE_OFFSET, Row.RETURN_BLANK_AS_NULL);
                if (cell == null)
                    continue;

                String atbName = POIUtil.getCellValue(row, ATTRIBUTE_OFFSET);
                String version = POIUtil.getCellValue(row, VERSION_OFFSET);

                // if  no version id and the atb has not been set, then set it
                // if a version and it matches the build version, set/overwrite the value 
                Attribute atb = null;

                // if version id is set and matches the launchParm setting, use it else skip 
                // a non-versioned atb may be encountered first, reuse it if received a versioned one
                if (version != null && version.length() > 0) {
                    if (!(launchParm.getVersion().equals(version))) {
                        continue;
                    }
                    logger.debug("add version specific atb " + ncClass.getClassName() + ", " + atbName + ", "
                            + version);
                    // if a default version has already been established, use it else create one
                    atb = ncClass.getAttribute(atbName);
                    if (atb == null) {
                        atb = new Attribute();
                    }
                } else { // no version, use existing if already set to the current version
                    atb = ncClass.getAttribute(atbName);
                    if (atb == null) {
                        atb = new Attribute();
                    } else
                        continue; // already established a version specific atb, ignore non-versioned entry
                }

                // create the Attributes and add to the class instance
                // TODO, verify not null on these required values, user may override Excel edits
                atb.setName(POIUtil.getCellValue(row, ATTRIBUTE_OFFSET));
                atb.setType(POIUtil.getCellValue(row, TYPE_OFFSET));
                atb.setLabel(POIUtil.getCellValue(row, LABEL_OFFSET));
                atb.setIndexName(POIUtil.getPopulatedCellValue(row, INDEXNAME_OFFSET));

                //logger.info("added NCClass atb " + ncClass.getClassName() + ", " + atb.getName());

                // defaults to false
                atb.setStore(UTIL.convertBoolean(POIUtil.getCellValue(row, STORE_OFFSET)));
                /*
                String storeVal = POIUtil.getPopulatedCellValue(row, STORE_OFFSET);
                if (storeVal != null) {
                   atb.setStore(new Boolean(storeVal));
                }
                */

                // analyzed is default value, will tokenize field
                String indexVal = POIUtil.getPopulatedCellValue(row, INDEX_OFFSET);
                if (indexVal != null) {
                    atb.setIndex(indexVal);
                }

                // default is true, don't set unless value is not
                String includeInAll = POIUtil.getPopulatedCellValue(row, INCLUDEINALL_OFFSET);
                if (includeInAll != null && includeInAll.equalsIgnoreCase("no")) {
                    atb.setIncludeInAll(false);
                }

                // default varies, based on the numeric type
                // TODO, verify numeric field
                String precision = POIUtil.getPopulatedCellValue(row, PRECISIONSTEP_OFFSET);
                if (precision != null) {
                    atb.setPrecision(new Integer(precision));
                }

                String dateFormat = POIUtil.getPopulatedCellValue(row, DATEFORMAT_OFFSET);
                if (dateFormat != null) {
                    atb.setDateFormat(dateFormat);
                }

                String fieldDataFormat = POIUtil.getPopulatedCellValue(row, FIELDDATAFORMAT_OFFSET);
                if (fieldDataFormat != null) {
                    atb.setFieldDataFormat(fieldDataFormat);
                }

                atb.setDocValues(UTIL.convertBoolean(POIUtil.getCellValue(row, DOCVALUES_OFFSET)));

                String boost = POIUtil.getPopulatedCellValue(row, BOOST_OFFSET);
                if (boost != null) {
                    atb.setBoost(new Double(boost));
                }

                // defaults to not adding the field to the JSON string
                String nullVal = POIUtil.getPopulatedCellValue(row, NULLVALUE_OFFSET);
                if (nullVal != null) {
                    atb.setNullValue(nullVal);
                }

                String termVector = POIUtil.getPopulatedCellValue(row, TERMVECTOR_OFFSET);
                if (termVector != null) {
                    atb.setTermVector(termVector);
                }

                String analyzer = POIUtil.getPopulatedCellValue(row, ANALYZER_OFFSET);
                if (analyzer != null) {
                    atb.setAnalyzer(analyzer);
                }

                String indexAnalyzer = POIUtil.getPopulatedCellValue(row, INDEX_ANALYZER_OFFSET);
                if (indexAnalyzer != null) {
                    atb.setIndexAnalyzer(indexAnalyzer);
                }

                String searchAnalyzer = POIUtil.getPopulatedCellValue(row, SEARCH_ANALYZER_OFFSET);
                if (searchAnalyzer != null) {
                    atb.setSearchAnalyzer(searchAnalyzer);
                }

                atb.setIgnoreAbove(UTIL.convertAnyNumberToInt(POIUtil.getCellValue(row, IGNOREABOVE_OFFSET)));
                atb.setPositionOffset(
                        UTIL.convertAnyNumberToInt(POIUtil.getCellValue(row, POSITIONGAP_OFFSET)));
                atb.setIgnoreMalformed(UTIL.convertBoolean(POIUtil.getCellValue(row, IGNOREMALFORMED_OFFSET)));
                atb.setCoerceNumber(UTIL.convertBoolean(POIUtil.getCellValue(row, COERCENUMBER_OFFSET)));
                atb.setBinaryCompress(UTIL.convertBoolean(POIUtil.getCellValue(row, BINARYCOMPRESS_OFFSET)));
                atb.setCompressThreshold(
                        UTIL.convertAnyNumberToInt(POIUtil.getCellValue(row, COMPRESSTHRESHOLD_OFFSET)));

                // TODO, all all the others

                //atb.setStore(UTIL.convertBoolean(POIUtil.getCellValue(row, STORE_OFFSET)));

                if (atb.getType().equalsIgnoreCase("SubType")) {
                    subTypes.put(atb.getName(), atb.getLabel());
                } else {
                    // save the attribute
                    ncClass.attributes.put(atb.getName(), atb);
                    ncClass.labels.put(atb.getLabel(), atb);

                    // if java class, verify the field accessibility
                    if (javaCls != null) {
                        Field field = null;
                        Class<?> current = javaCls;
                        while (!(current.getName().equals("java.lang.Object"))) {
                            try {
                                field = current.getDeclaredField(atb.getName());
                                atb.setField(field);
                                //atb.setField(current.getDeclaredField(atb.getName()));
                                break;
                            } catch (Exception e) {
                                //System.out.println("java reflection warning, class/field not found, checking super class " + cls.getName() + ", " + atb.getName());
                                current = current.getSuperclass();
                                continue;
                            }
                        }

                        if (field != null) {
                            field.setAccessible(true);
                        }
                    }
                }
            }
            i--; // continue the loop on the prior row
        }
    } catch (Exception e) {
        String msg = "exception in NCClass load " + e.toString();
        logger.error(msg);
        throw new Exception(msg);
    }
}

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

static private Field findField(Class<?> startClass, String fieldName) {
    Class<?> use = startClass;
    Field field = null;//from ww w  .j a  v a2s  .  com
    while (field == null) {
        try {
            field = use.getDeclaredField(fieldName);
        } catch (NoSuchFieldException e) {
            if (KDSmartDbEntity.class.equals(use)) {
                break;
            }
            use = use.getSuperclass();
        }
    }
    if (field == null) {
        throw new IllegalArgumentException("No such field: " + startClass.getSimpleName() + "." + fieldName);
    }

    return field;
}

From source file:me.StevenLawson.TotalFreedomMod.TFM_Util.java

@SuppressWarnings("unchecked")
public static <T> T getField(Object from, String name) {
    Class<?> checkClass = from.getClass();
    do {/*from w  ww  .  ja  v a 2  s.c  o m*/
        try {
            Field field = checkClass.getDeclaredField(name);
            field.setAccessible(true);
            return (T) field.get(from);

        } catch (NoSuchFieldException ex) {
        } catch (IllegalAccessException ex) {
        }
    } while (checkClass.getSuperclass() != Object.class && ((checkClass = checkClass.getSuperclass()) != null));

    return null;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Get the value of a declared field on an object
 *
 * @param obj/*from  w  ww  .  j  ava  2  s  .c om*/
 * @param name
 * @return The object value or null if there is no such field or access problems
 */
public static Object getFieldValue(Object obj, String name) {
    Class clazz = obj.getClass();
    Field f = null;
    try {
        f = clazz.getDeclaredField(name);
        return f.get(obj);
    } catch (Exception e) {
        return null;
    }
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Work out if the specified object has a public field with the name supplied.
 *
 * @param obj//from  www .  ja va 2s.  co m
 * @param name
 * @return True if a public field with the name exists
 */
public static boolean isPublicField(Object obj, String name) {
    Class clazz = obj.getClass();
    Field f = null;
    try {
        f = clazz.getDeclaredField(name);
        return Modifier.isPublic(f.getModifiers());
    } catch (NoSuchFieldException e) {
        return false;
    }
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleSheetTest.java

@SuppressWarnings("unchecked")
private static <T> T get(final Object o, final Class<?> c, final String fieldName) {
    try {//from   w  w  w. j  a v a2  s.  com
        final Field field = c.getDeclaredField(fieldName);
        field.setAccessible(true);
        return (T) field.get(o);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}