Example usage for java.lang.reflect Field setInt

List of usage examples for java.lang.reflect Field setInt

Introduction

In this page you can find the example usage for java.lang.reflect Field setInt.

Prototype

@CallerSensitive
@ForceInline 
public void setInt(Object obj, int i) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Sets the value of a field as an int on the specified object.

Usage

From source file:org.wso2.carbon.identity.openidconnect.DefaultOIDCClaimsCallbackHandlerTest.java

private void setStaticField(Class classname, String fieldName, Object value)
        throws NoSuchFieldException, IllegalAccessException {

    Field declaredField = classname.getDeclaredField(fieldName);
    declaredField.setAccessible(true);/*from  w  w w.j  a  v  a2s.  co  m*/

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(declaredField, declaredField.getModifiers() & ~Modifier.FINAL);

    declaredField.set(null, value);
}

From source file:com.quarterfull.newsAndroid.NewsReaderListActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    ThemeChooser.chooseTheme(this);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_newsreader);

    ButterKnife.bind(this);

    if (toolbar != null) {
        setSupportActionBar(toolbar);//from w  w w .ja  v a2 s  .  c o  m
    }

    initAccountManager();

    //Init config --> if nothing is configured start the login dialog.
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    if (mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null) == null)
        StartLoginFragment(NewsReaderListActivity.this);

    Bundle args = new Bundle();
    String userName = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null);
    String url = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null);
    args.putString("accountName", String.format("%s\n%s", userName, url));
    NewsReaderListFragment newsReaderListFragment = new NewsReaderListFragment();
    newsReaderListFragment.setArguments(args);
    // Insert the fragment by replacing any existing fragment
    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.left_drawer, newsReaderListFragment).commit();

    if (drawerLayout != null) {
        drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.empty_view_content,
                R.string.empty_view_content) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                togglePodcastVideoViewAnimation();

                syncState();
                EventBus.getDefault().post(new FeedPanelSlideEvent(false));
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                togglePodcastVideoViewAnimation();
                reloadCountNumbersOfSlidingPaneAdapter();

                syncState();

                showTapLogoToSyncShowcaseView();
            }
        };

        drawerLayout.setDrawerListener(drawerToggle);

        try {
            // increase the size of the drag margin to prevent starting a star swipe when
            // trying to open the drawer.
            Field mDragger = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            mDragger.setAccessible(true);
            ViewDragHelper draggerObj = (ViewDragHelper) mDragger.get(drawerLayout);

            Field mEdgeSize = draggerObj.getClass().getDeclaredField("mEdgeSize");
            mEdgeSize.setAccessible(true);
            int edge = mEdgeSize.getInt(draggerObj);

            mEdgeSize.setInt(draggerObj, edge * 3);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayShowHomeEnabled(true);
    if (drawerToggle != null)
        drawerToggle.syncState();

    if (savedInstanceState == null)//When the app starts (no orientation change)
    {
        StartDetailFragment(SubscriptionExpandableListAdapter.SPECIAL_FOLDERS.ALL_UNREAD_ITEMS.getValue(), true,
                null, true);
    }

    //AppRater.app_launched(this);
    //AppRater.rateNow(this);

    UpdateButtonLayout();
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

protected void setField(Field field, String val) {
    try {//from ww  w. j  a v  a  2  s.c  o  m
        // deal with IllegalAccessException
        field.setAccessible(true);
        if (field.getType() == String.class) {
            field.set(this, val);
        } else {
            Method setter = null;
            try {
                setter = this.getClass().getMethod("set" + StringUtil.getTitleCase(field.getName()),
                        String.class);
            } catch (Exception e) {

            }
            if (null != setter) {
                setter.setAccessible(true);
                setter.invoke(this, val);
            } else if (field.getType() == Integer.TYPE) {
                field.setInt(this, Integer.parseInt(val));
            } else if (field.getType() == Float.TYPE) {
                field.setFloat(this, Float.parseFloat(val));

            } else if (field.getType() == Double.TYPE) {
                field.setDouble(this, Double.parseDouble(val));

            } else if (field.getType() == Long.TYPE) {
                field.setLong(this, Long.parseLong(val));

            } else if (field.getType() == Boolean.TYPE) {
                Boolean bval = StringUtils.isBlank(val) ? null
                        : NumberUtils.isNumber(val) ? (Integer.parseInt(val) != 0)
                                : Boolean.parseBoolean(val) || val.equalsIgnoreCase("T")
                                        || val.equalsIgnoreCase("Y") || val.equalsIgnoreCase("YES");

                field.setBoolean(this, bval);

            } else if (field.getType() == Short.TYPE) {
                field.setShort(this, Short.parseShort(val));
            } else if (field.getType() == Date.class) {
                Date dVal = null;
                try {
                    dVal =

                            StringUtils.isBlank(val) ? null
                                    : NumberUtils.isNumber(val) ? DateUtil.getDate(Integer.parseInt(val))
                                            : DateUtil.parseDate(val, "MM/dd/yyyy");
                } catch (ParseException e) {
                    logger.error("Expected date in MM/dd/yyyy format.", e);
                }
                field.set(this, dVal);
            }
        }
    } catch (IllegalArgumentException e) {
        logger.error("Unable to fill random data in field " + field.getName(), e);
    } catch (IllegalAccessException e) {
        logger.error("Unable to Access " + field.getName(), e);
    } catch (InvocationTargetException e) {
        logger.error("Unable to invoke setter for " + field.getName(), e);
    }

}

From source file:me.henrytao.observableorm.orm.ObservableModel.java

public T deserialize(Map<String, Object> map) throws IllegalAccessException {
    Field[] fields = getDeclaredFields();
    for (Field f : fields) {
        if (!f.isAnnotationPresent(Column.class)) {
            continue;
        }//ww w .  ja  v a 2s.c om
        Column column = f.getAnnotation(Column.class);
        if (!column.deserialize()) {
            continue;
        }
        f.setAccessible(true);
        String name = column.name();
        Object value = map.get(name);
        Class type = f.getType();
        Deserializer deserializer = deserializerMap.get(type);
        if (deserializer != null) {
            f.set(this, deserializer.deserialize(value));
        } else if (boolean.class.isAssignableFrom(type)) {
            f.setBoolean(this, value == null ? false : (Boolean) value);
        } else if (double.class.isAssignableFrom(type)) {
            f.setDouble(this, value == null ? 0.0 : (Double) value);
        } else if (float.class.isAssignableFrom(type)) {
            f.setFloat(this, value == null ? 0f : (Float) value);
        } else if (int.class.isAssignableFrom(type)) {
            f.setInt(this, value == null ? 0 : (int) value);
        } else if (short.class.isAssignableFrom(type)) {
            f.setShort(this, value == null ? 0 : (short) value);
        } else if (byte.class.isAssignableFrom(type)) {
            f.setByte(this, value == null ? 0 : (byte) value);
        } else if (String.class.isAssignableFrom(type)) {
            f.set(this, value);
        } else if (JSONObject.class.isAssignableFrom(type)) {
            // todo: nested object should be another model
        }
    }
    return (T) this;
}

From source file:lineage2.gameserver.Config.java

/**
 * Method setField.//from  w  w  w .java 2s.  c om
 * @param fieldName String
 * @param value String
 * @return boolean
 */
public static boolean setField(String fieldName, String value) {
    Field field = FieldUtils.getField(Config.class, fieldName);
    if (field == null) {
        return false;
    }
    try {
        if (field.getType() == boolean.class) {
            field.setBoolean(null, BooleanUtils.toBoolean(value));
        } else if (field.getType() == int.class) {
            field.setInt(null, NumberUtils.toInt(value));
        } else if (field.getType() == long.class) {
            field.setLong(null, NumberUtils.toLong(value));
        } else if (field.getType() == double.class) {
            field.setDouble(null, NumberUtils.toDouble(value));
        } else if (field.getType() == String.class) {
            field.set(null, value);
        } else {
            return false;
        }
    } catch (IllegalArgumentException e) {
        return false;
    } catch (IllegalAccessException e) {
        return false;
    }
    return true;
}

From source file:com.sikulix.core.SX.java

private static void setOptions(PropertiesConfiguration someOptions) {
    if (isNull(someOptions) || someOptions.size() == 0) {
        return;/*from  w  ww.  ja v  a  2  s. co  m*/
    }
    Iterator<String> allKeys = someOptions.getKeys();
    List<String> sxSettings = new ArrayList<>();
    while (allKeys.hasNext()) {
        String key = allKeys.next();
        if (key.startsWith("Settings.")) {
            sxSettings.add(key);
            continue;
        }
        trace("!setOptions: %s = %s", key, someOptions.getProperty(key));
    }
    if (sxSettings.size() > 0) {
        Class cClass = null;
        try {
            cClass = Class.forName("org.sikuli.basics.Settings");
        } catch (ClassNotFoundException e) {
            error("!setOptions: %s", cClass);
        }
        if (!isNull(cClass)) {
            for (String sKey : sxSettings) {
                String sAttr = sKey.substring("Settings.".length());
                Field cField = null;
                Class ccField = null;
                try {
                    cField = cClass.getField(sAttr);
                    ccField = cField.getType();
                    if (ccField.getName() == "boolean") {
                        cField.setBoolean(null, someOptions.getBoolean(sKey));
                    } else if (ccField.getName() == "int") {
                        cField.setInt(null, someOptions.getInt(sKey));
                    } else if (ccField.getName() == "float") {
                        cField.setFloat(null, someOptions.getFloat(sKey));
                    } else if (ccField.getName() == "double") {
                        cField.setDouble(null, someOptions.getDouble(sKey));
                    } else if (ccField.getName() == "String") {
                        cField.set(null, someOptions.getString(sKey));
                    }
                    trace("!setOptions: %s = %s", sAttr, someOptions.getProperty(sKey));
                    someOptions.clearProperty(sKey);
                } catch (Exception ex) {
                    error("!setOptions: %s = %s", sKey, sxOptions.getProperty(sKey));
                }
            }
        }
    }
}

From source file:org.apache.hadoop.hbase.client.TestHCM.java

private int setNumTries(HConnectionImplementation hci, int newVal) throws Exception {
    Field numTries = hci.getClass().getDeclaredField("numTries");
    numTries.setAccessible(true);/*from  www . jav  a 2  s.  c o  m*/
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(numTries, numTries.getModifiers() & ~Modifier.FINAL);
    final int prevNumRetriesVal = (Integer) numTries.get(hci);
    numTries.set(hci, newVal);

    return prevNumRetriesVal;
}

From source file:cn.edu.zafu.corepage.base.BaseActivity.java

/**
 * ???//from w  w  w  .jav  a  2 s .co  m
 *
 * @param savedInstanceState Bundle
 */
private void loadActivitySavedData(Bundle savedInstanceState) {
    Field[] fields = this.getClass().getDeclaredFields();
    Field.setAccessible(fields, true);
    Annotation[] ans;
    for (Field f : fields) {
        ans = f.getDeclaredAnnotations();
        for (Annotation an : ans) {
            if (an instanceof SaveWithActivity) {
                try {
                    String fieldName = f.getName();
                    @SuppressWarnings("rawtypes")
                    Class cls = f.getType();
                    if (cls == int.class || cls == Integer.class) {
                        f.setInt(this, savedInstanceState.getInt(fieldName));
                    } else if (String.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getString(fieldName));
                    } else if (Serializable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getSerializable(fieldName));
                    } else if (cls == long.class || cls == Long.class) {
                        f.setLong(this, savedInstanceState.getLong(fieldName));
                    } else if (cls == short.class || cls == Short.class) {
                        f.setShort(this, savedInstanceState.getShort(fieldName));
                    } else if (cls == boolean.class || cls == Boolean.class) {
                        f.setBoolean(this, savedInstanceState.getBoolean(fieldName));
                    } else if (cls == byte.class || cls == Byte.class) {
                        f.setByte(this, savedInstanceState.getByte(fieldName));
                    } else if (cls == char.class || cls == Character.class) {
                        f.setChar(this, savedInstanceState.getChar(fieldName));
                    } else if (CharSequence.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getCharSequence(fieldName));
                    } else if (cls == float.class || cls == Float.class) {
                        f.setFloat(this, savedInstanceState.getFloat(fieldName));
                    } else if (cls == double.class || cls == Double.class) {
                        f.setDouble(this, savedInstanceState.getDouble(fieldName));
                    } else if (String[].class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getStringArray(fieldName));
                    } else if (Parcelable.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getParcelable(fieldName));
                    } else if (Bundle.class.isAssignableFrom(cls)) {
                        f.set(this, savedInstanceState.getBundle(fieldName));
                    }
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.apache.hive.jdbc.TestJdbcWithMiniHS2.java

private void setReflectionUtilCache() {
    Field constructorCacheField;/*w  w  w.jav  a2  s.com*/
    Cache<Class<?>, Constructor<?>> tmp;
    try {
        constructorCacheField = ReflectionUtil.class.getDeclaredField("CONSTRUCTOR_CACHE");
        if (constructorCacheField != null) {
            constructorCacheField.setAccessible(true);
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(constructorCacheField,
                    constructorCacheField.getModifiers() & ~Modifier.FINAL);
            tmp = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).concurrencyLevel(64)
                    .weakKeys().weakValues().build();
            constructorCacheField.set(tmp.getClass(), tmp);
        }
    } catch (Exception e) {
        System.out.println("Error when setting the CONSTRUCTOR_CACHE to expire: " + e);
    }
}

From source file:org.wso2.carbon.identity.oauth.endpoint.authz.OAuth2AuthzEndpointTest.java

@Test(dataProvider = "providePathExistsData")
public void testGetFormPostRedirectPage(String carbonHome, boolean fileExists) throws Exception {
    spy(CarbonUtils.class);
    doReturn(carbonHome).when(CarbonUtils.class, "getCarbonHome");

    Method getFormPostRedirectPage = authzEndpointObject.getClass()
            .getDeclaredMethod("getFormPostRedirectPage");
    getFormPostRedirectPage.setAccessible(true);
    String value = (String) getFormPostRedirectPage.invoke(authzEndpointObject);
    assertEquals((value != null), fileExists, "FormPostRedirectPage value is incorrect");

    Field formPostRedirectPage = authzEndpointObject.getClass().getDeclaredField("formPostRedirectPage");

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);//from w w  w  .ja va2s .c o  m
    modifiersField.setInt(formPostRedirectPage, formPostRedirectPage.getModifiers() & ~Modifier.FINAL);
    formPostRedirectPage.setAccessible(true);
    formPostRedirectPage.set(authzEndpointObject, value);

    Method createFormPage = authzEndpointObject.getClass().getDeclaredMethod("createFormPage", String.class,
            String.class, String.class, String.class);
    createFormPage.setAccessible(true);
    value = (String) createFormPage.invoke(authzEndpointObject, APP_REDIRECT_URL_JSON, APP_REDIRECT_URL,
            StringUtils.EMPTY, "sessionDataValue");
    assertNotNull(value, "Form post page is null");
}