Example usage for java.lang Class getField

List of usage examples for java.lang Class getField

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:tk.eatheat.omnisnitch.ui.SwitchLayout.java

@SuppressWarnings("rawtypes")
public SwitchLayout(Context context) {
    mContext = context;//from  w  w  w  . j  av  a  2  s  . c om
    mWindowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
    mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
    mConfiguration = SwitchConfiguration.getInstance(mContext);

    mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mLoadedTasks = new ArrayList<TaskDescription>();
    mRecentListAdapter = new RecentListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mLoadedTasks);
    mFavoriteList = new ArrayList<String>();
    mFavoriteListAdapter = new FavoriteListAdapter(mContext, android.R.layout.simple_list_item_multiple_choice,
            mFavoriteList);

    final ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    am.getMemoryInfo(mMemInfo);
    String sClassName = "android.app.ActivityManager";
    try {
        Class classToInvestigate = Class.forName(sClassName);
        Class[] classes = classToInvestigate.getDeclaredClasses();
        for (int i = 0; i < classes.length; i++) {
            Class c = classes[i];
            if (c.getName().equals("android.app.ActivityManager$MemoryInfo")) {
                String strNewFieldName = "secondaryServerThreshold";
                Field field = c.getField(strNewFieldName);
                mSecServerMem = field.getLong(mMemInfo);
                break;
            }
        }
    } catch (ClassNotFoundException e) {
    } catch (NoSuchFieldException e) {
    } catch (Exception e) {
    }
}

From source file:com.guodong.sun.guodong.widget.ZoomImageView.java

/**
 * ???// www .  ja v  a2s .  c  o  m
 *
 * @return
 */
private int getStatusBarHeight(Context context) {
    Class<?> c = null;
    Object obj = null;
    java.lang.reflect.Field field = null;
    int x = 0;
    int statusBarHeight = 0;
    try {
        c = Class.forName("com.android.internal.R$dimen");
        obj = c.newInstance();
        field = c.getField("status_bar_height");
        x = Integer.parseInt(field.get(obj).toString());
        statusBarHeight = context.getResources().getDimensionPixelSize(x);
        return statusBarHeight;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return statusBarHeight;
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

private static Object getStaticFieldValue(final Class bean, final String name) {
    try {//from w ww.j a  v  a 2 s.  c  o m
        Field field = bean.getField(name);
        return field.get(null);
    } catch (NoSuchFieldException e) {
        return null;
    } catch (SecurityException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (IllegalAccessException e) {
        return null;
    }
}

From source file:lineage2.gameserver.Config.java

/**
 * Method loadGMAccess./*from  w  w w .  ja v a  2  s.  c  o  m*/
 * @param file File
 */
public static void loadGMAccess(File file) {
    try {
        Field fld;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setValidating(false);
        factory.setIgnoringComments(true);
        Document doc = factory.newDocumentBuilder().parse(file);
        for (Node z = doc.getFirstChild(); z != null; z = z.getNextSibling()) {
            for (Node n = z.getFirstChild(); n != null; n = n.getNextSibling()) {
                if (!n.getNodeName().equalsIgnoreCase("char")) {
                    continue;
                }
                PlayerAccess pa = new PlayerAccess();
                for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) {
                    Class<?> cls = pa.getClass();
                    String node = d.getNodeName();
                    if (node.equalsIgnoreCase("#text")) {
                        continue;
                    }
                    try {
                        fld = cls.getField(node);
                    } catch (NoSuchFieldException e) {
                        _log.info("Not found desclarate ACCESS name: " + node + " in XML Player access Object");
                        continue;
                    }
                    if (fld.getType().getName().equalsIgnoreCase("boolean")) {
                        fld.setBoolean(pa,
                                Boolean.parseBoolean(d.getAttributes().getNamedItem("set").getNodeValue()));
                    } else if (fld.getType().getName().equalsIgnoreCase("int")) {
                        fld.setInt(pa, Integer.valueOf(d.getAttributes().getNamedItem("set").getNodeValue()));
                    }
                }
                gmlist.put(pa.PlayerID, pa);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ubic.gemma.web.taglib.ConstantsTag.java

@Override
public int doStartTag() throws JspException {
    // Using reflection, get the available field names in the class
    Class<?> c;
    int toScope = PageContext.PAGE_SCOPE;

    if (scope != null) {
        toScope = getScope(scope);//  ww w .ja v  a2  s .c  o m
    }

    try {
        c = Class.forName(clazz);
    } catch (ClassNotFoundException cnf) {
        log.error("ClassNotFound - maybe a typo?");
        throw new JspException(cnf.getMessage());
    }

    try {
        // if var is null, expose all variables
        if (var == null) {
            Field[] fields = c.getDeclaredFields();

            AccessibleObject.setAccessible(fields, true);

            for (Field field : fields) {
                /*
                 * if (log.isDebugEnabled()) { log.debug("putting '" + fields[i].getName() + "=" +
                 * fields[i].get(this) + "' into " + scope + " scope"); }
                 */
                pageContext.setAttribute(field.getName(), field.get(this), toScope);
            }
        } else {
            try {
                String value = (String) c.getField(var).get(this);
                pageContext.setAttribute(c.getField(var).getName(), value, toScope);
            } catch (NoSuchFieldException nsf) {
                log.error(nsf.getMessage());
                throw new JspException(nsf);
            }
        }
    } catch (IllegalAccessException iae) {
        log.error("Illegal Access Exception - maybe a classloader issue?");
        throw new JspException(iae);
    }

    // Continue processing this page
    return (SKIP_BODY);
}

From source file:de.innovationgate.webgate.api.WGFactory.java

/**
 * retrieves all metainfos of the given class
 * @param c/*from   w  w  w. j  a  v a  2s  .c o m*/
 * @return Map of meta infos
 */
private Map<String, MetaInfo> gatherMetaInfos(Class<? extends MetaInfoProvider> c) {
    Map<String, MetaInfo> map = new HashMap<String, MetaInfo>();
    Field[] fields = c.getFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.getName().startsWith("META_")) {
            try {
                String metaName = (String) field.get(null);
                String metaInfoFieldName = "METAINFO_" + field.getName().substring(5, field.getName().length());
                Field metaInfoField = c.getField(metaInfoFieldName);
                MetaInfo metaInfo = (MetaInfo) metaInfoField.get(null);
                // check info
                if (!metaName.equals(metaInfo.getName())) {
                    throw new RuntimeException(
                            "Unable to initialize metadata-framework. MetaInfo for metafield '"
                                    + field.getName() + "' of class ' " + c.getName()
                                    + "' is invalid. Name mismatch!.");
                }
                metaInfo.setDefiningClass(c);
                map.put(metaName, metaInfo);

            } catch (IllegalAccessException e) {
                throw new RuntimeException("Unable to initialize metadata-framework.", e);
            } catch (SecurityException e) {
                throw new RuntimeException("Unable to initialize metadata-framework.", e);
            } catch (NoSuchFieldException e) {
                throw new RuntimeException("Unable to initialize metadata-framework. MetaInfo for metafield '"
                        + field.getName() + "' of class '" + c.getName() + "' not found.", e);
            }
        }
    }
    return map;
}

From source file:com.streamsets.datacollector.execution.preview.sync.SyncPreviewer.java

private RawSourcePreviewer createRawSourcePreviewer(StageDefinition sourceStageDef,
        MultivaluedMap<String, String> previewParams) throws PipelineRuntimeException, PipelineStoreException {

    RawSourceDefinition rawSourceDefinition = sourceStageDef.getRawSourceDefinition();
    List<ConfigDefinition> configDefinitions = rawSourceDefinition.getConfigDefinitions();

    validateParameters(previewParams, configDefinitions);

    //Attempt to load the previewer class from stage class loader
    Class previewerClass;
    try {//from   w  w w .  j a va 2 s . com
        previewerClass = sourceStageDef.getStageClassLoader()
                .loadClass(sourceStageDef.getRawSourceDefinition().getRawSourcePreviewerClass());
    } catch (ClassNotFoundException e) {
        //Try loading from this class loader
        try {
            previewerClass = getClass().getClassLoader()
                    .loadClass(sourceStageDef.getRawSourceDefinition().getRawSourcePreviewerClass());
        } catch (ClassNotFoundException e1) {
            throw new RuntimeException(e1);
        }
    }

    RawSourcePreviewer rawSourcePreviewer;
    try {
        rawSourcePreviewer = (RawSourcePreviewer) previewerClass.newInstance();
        //inject values from url to fields in the rawSourcePreviewer
        for (ConfigDefinition confDef : configDefinitions) {
            Field f = previewerClass.getField(confDef.getFieldName());
            f.set(rawSourcePreviewer, getValueFromParam(f, previewParams.get(confDef.getName()).get(0)));
        }
        rawSourcePreviewer.setMimeType(rawSourceDefinition.getMimeType());
    } catch (IllegalAccessException | InstantiationException | NoSuchFieldException e) {
        throw new RuntimeException(e);
    }
    return rawSourcePreviewer;
}

From source file:com.indoorsy.frash.easemob.activity.ChatActivity.java

/**
 * ?gridview?view//w  w  w .  ja v a 2 s .c o m
 * 
 * @param i
 * @return
 */
private View getGridChildView(int i) {
    View view = View.inflate(this, R.layout.expression_gridview, null);
    ExpandGridView gv = (ExpandGridView) view.findViewById(R.id.gridview);
    List<String> list = new ArrayList<String>();
    if (i == 1) {
        List<String> list1 = reslist.subList(0, 20);
        list.addAll(list1);
    } else if (i == 2) {
        list.addAll(reslist.subList(20, reslist.size()));
    }
    list.add("delete_expression");
    final ExpressionAdapter expressionAdapter = new ExpressionAdapter(this, 1, list);
    gv.setAdapter(expressionAdapter);
    gv.setOnItemClickListener(new OnItemClickListener() {

        @SuppressWarnings("rawtypes")
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            String filename = expressionAdapter.getItem(position);
            try {
                // ????
                // ?????
                if (buttonSetModeKeyboard.getVisibility() != View.VISIBLE) {

                    if (filename != "delete_expression") { // ?
                        // ????SmileUtils
                        Class clz = Class.forName("com.indoorsy.frash.easemob.util.SmileUtils");
                        Field field = clz.getField(filename);
                        mEditTextContent
                                .append(SmileUtils.getSmiledText(ChatActivity.this, (String) field.get(null)));
                    } else { // 
                        if (!TextUtils.isEmpty(mEditTextContent.getText())) {

                            int selectionStart = mEditTextContent.getSelectionStart();// ??
                            if (selectionStart > 0) {
                                String body = mEditTextContent.getText().toString();
                                String tempStr = body.substring(0, selectionStart);
                                int i = tempStr.lastIndexOf("[");// ???
                                if (i != -1) {
                                    CharSequence cs = tempStr.substring(i, selectionStart);
                                    if (SmileUtils.containsKey(cs.toString()))
                                        mEditTextContent.getEditableText().delete(i, selectionStart);
                                    else
                                        mEditTextContent.getEditableText().delete(selectionStart - 1,
                                                selectionStart);
                                } else {
                                    mEditTextContent.getEditableText().delete(selectionStart - 1,
                                            selectionStart);
                                }
                            }
                        }

                    }
                }
            } catch (Exception e) {
            }

        }
    });
    return view;
}

From source file:io.stallion.dataAccess.db.DB.java

public Schema modelToSchema(Class cls) {
    try {/* w w w.java  2 s .c o  m*/
        Field metaField = cls.getField("meta");
        if (metaField != null) {
            Map<String, Object> o = (Map<String, Object>) metaField.get(null);
            if (o != null && !empty(o.getOrDefault("tableName", "").toString())) {
                return metaDataModelToSchema(cls, o);
            }
        }
    } catch (NoSuchFieldException e) {
        Log.exception(e, "Error finding meta field");
    } catch (IllegalAccessException e) {
        Log.exception(e, "Error accesing meta field");
    }
    return annotatedModelToSchema(cls);
}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

protected void addResultTypes(PackageConfig.Builder packageContext, Element element) {
    NodeList resultTypeList = element.getElementsByTagName("result-type");

    for (int i = 0; i < resultTypeList.getLength(); i++) {
        Element resultTypeElement = (Element) resultTypeList.item(i);
        String name = resultTypeElement.getAttribute("name");
        String className = resultTypeElement.getAttribute("class");
        String def = resultTypeElement.getAttribute("default");

        Location loc = DomHelper.getLocationObject(resultTypeElement);

        Class clazz = verifyResultType(className, loc);
        if (clazz != null) {
            String paramName = null;
            try {
                paramName = (String) clazz.getField("DEFAULT_PARAM").get(null);
            } catch (Throwable t) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("The result type [#0] doesn't have a default param [DEFAULT_PARAM] defined!", t,
                            className);/* w w w . j a v  a 2s . c  o m*/
                }
            }
            ResultTypeConfig.Builder resultType = new ResultTypeConfig.Builder(name, className)
                    .defaultResultParam(paramName).location(DomHelper.getLocationObject(resultTypeElement));

            Map<String, String> params = XmlHelper.getParams(resultTypeElement);

            if (!params.isEmpty()) {
                resultType.addParams(params);
            }
            packageContext.addResultTypeConfig(resultType.build());

            // set the default result type
            if ("true".equals(def)) {
                packageContext.defaultResultType(name);
            }
        }
    }
}