Example usage for java.lang.reflect Field getInt

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public int getInt(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion.

Usage

From source file:com.jkoolcloud.tnt4j.streams.fields.ActivityInfo.java

private static String formatArrayPattern(String pattern, Object[] vArray) {
    MessageFormat mf = new MessageFormat(pattern);

    try {//from   w  w  w .  j av  a  2s .  c  o m
        Field f = mf.getClass().getDeclaredField("maxOffset");
        f.setAccessible(true);
        int maxOffset = f.getInt(mf);
        if (maxOffset >= 0) {
            f = mf.getClass().getDeclaredField("argumentNumbers");
            f.setAccessible(true);
            int[] ana = (int[]) f.get(mf);
            int maxIndex = ana[maxOffset];

            if (maxIndex >= vArray.length) {
                LOGGER.log(OpLevel.WARNING,
                        StreamsResources.getString(StreamsResources.RESOURCE_BUNDLE_NAME,
                                "ActivityInfo.formatting.arguments.mismatch"),
                        pattern, maxIndex, ArrayUtils.getLength(vArray));
            }
        }
    } catch (Exception exc) {
    }

    return mf.format(vArray);
}

From source file:at.treedb.backup.Export.java

/**
 * Dumps all entities of the database, or just all entities of a domain to
 * the archive./* w  w w .j ava2  s. c  o  m*/
 * 
 * @param clazz
 *            entity to be dumped
 * @param domain
 *            optional domain, or {@code null} for dumping all entities of
 *            the database to the archive
 * @param backupType
 *            type of the backup
 * @throws Exception
 */
private void dumpClass(DBexportInfo dbInfo, Class<?> clazz, Domain domain, DBexportInfo.BACKUP_TYPE backupType)
        throws Exception {
    String archivePath = ROOT_DIR + clazz.getSimpleName() + "/";
    createDirEntry(archivePath, date);

    Iterator iter = new Iterator(dao, clazz, domain, status, entityFetchThreshold);
    int blockCounter = 0;
    switch (serialization) {
    case JSON:
        gson = new Gson();
        break;
    case XML:
        xstream = new XStream();
        break;
    default:
        break;
    }
    dbInfo.addEntityCount(clazz.getSimpleName() + ":" + iter.getEntitiesNum());
    ArrayList<Field> fieldList = new ArrayList<Field>();
    boolean userFields = false;
    if (backupType == DBexportInfo.BACKUP_TYPE.DOMAIN) {
        userFields = collectUserFields(clazz, fieldList);
        if (clazz.getSuperclass() != null) {
            collectUserFields(clazz.getSuperclass(), fieldList);
        }
    }
    if (fieldList.size() > 0) {
        userFields = true;
    }

    boolean singleStep = false;
    if (clazz.equals(CIblob.class)) {
        singleStep = true;
    }

    while (iter.hasNext()) {
        List<Object> l = null;
        if (!singleStep) {
            l = iter.next();
            l = detachBinaryData(dao, clazz, l);
        } else {
            ArrayList<Object> list = new ArrayList<Object>();
            for (int i = 0; i < entityFetchThreshold; ++i) {
                l = iter.nextObject();
                if (l == null) {
                    break;
                }
                l = detachBinaryData(dao, clazz, l);
                list.add(l.get(0));
            }
            if (list.size() == 0) {
                continue;
            }
            l = list;
        }

        SevenZArchiveEntry entry = new SevenZArchiveEntry();
        entry = new SevenZArchiveEntry();
        entry.setName(archivePath + blockCounter++);
        entry.setAccessDate(date);
        entry.setCreationDate(date);
        entry.setLastModifiedDate(date);
        entry.setDirectory(false);
        sevenZOutput.putArchiveEntry(entry);
        byte[] byteStream = null;
        switch (serialization) {
        case JSON:
            byteStream = gson.toJson(l).getBytes();
            break;
        case XML:
            byteStream = xstream.toXML(l).getBytes();
            break;
        case BINARY:
            ByteArrayOutputStream bs = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(bs);
            out.writeObject(l);
            out.close();
            byteStream = bs.toByteArray();
            break;
        }
        // collect all user references
        if (userFields) {
            for (Object o : l) {
                for (Field f : fieldList) {
                    f.setAccessible(true);
                    userIDs.add(f.getInt(o));
                }
            }
        }
        sevenZOutput.write(byteStream);
        sevenZOutput.closeArchiveEntry();
        if (l instanceof CIblob) {
            if (dao.isJPA() && dao.getJPAimpl() == DAO.JPA_IMPL.ECLIPSELINK) {
                dao.clear();
            } else {
                dao.detach(l);
            }
            ((CIblob) l).resetBlob();
        }
        l = null;

    }
    iter.close();
}

From source file:net.pms.service.ProcessManager.java

/**
 * Retrieves the process ID (PID) for the specified {@link Process}.
 *
 * @param process the {@link Process} for whose PID to retrieve.
 * @return The PID or zero if the PID couldn't be retrieved.
 *///  w  ww.  j  a  v  a2s.  c o  m
public static int getProcessId(@Nullable Process process) {
    if (process == null) {
        return 0;
    }
    try {
        Field field;
        if (Platform.isWindows()) {
            field = process.getClass().getDeclaredField("handle");
            field.setAccessible(true);
            int pid = Kernel32.INSTANCE.GetProcessId(new HANDLE(new Pointer(field.getLong(process))));
            if (pid == 0 && LOGGER.isDebugEnabled()) {
                int lastError = Kernel32.INSTANCE.GetLastError();
                LOGGER.debug("KERNEL32.getProcessId() failed with error {}", lastError);
            }
            return pid;
        }
        field = process.getClass().getDeclaredField("pid");
        field.setAccessible(true);
        return field.getInt(process);
    } catch (Exception e) {
        LOGGER.warn("Failed to get process id for process \"{}\": {}", process, e.getMessage());
        LOGGER.trace("", e);
        return 0;
    }
}

From source file:com.facebook.react.views.textinput.ReactTextInputManager.java

private void setCursorColor(ReactEditText view, @Nullable Integer color) {
    // Evil method that uses reflection because there is no public API to changes
    // the cursor color programmatically.
    // Based on http://stackoverflow.com/questions/25996032/how-to-change-programatically-edittext-cursor-color-in-android.
    try {/*from  ww  w. j  ava 2s  .com*/
        // Get the original cursor drawable resource.
        Field cursorDrawableResField = TextView.class.getDeclaredField("mCursorDrawableRes");
        cursorDrawableResField.setAccessible(true);
        int drawableResId = cursorDrawableResField.getInt(view);

        Drawable drawable = ContextCompat.getDrawable(view.getContext(), drawableResId);
        if (color != null) {
            drawable.setColorFilter(color, PorterDuff.Mode.SRC_IN);
        }
        Drawable[] drawables = { drawable, drawable };

        // Update the current cursor drawable with the new one.
        Field editorField = TextView.class.getDeclaredField("mEditor");
        editorField.setAccessible(true);
        Object editor = editorField.get(view);
        Field cursorDrawableField = editor.getClass().getDeclaredField("mCursorDrawable");
        cursorDrawableField.setAccessible(true);
        cursorDrawableField.set(editor, drawables);
    } catch (NoSuchFieldException ex) {
        // Ignore errors to avoid crashing if these private fields don't exist on modified
        // or future android versions.
    } catch (IllegalAccessException ex) {
    }
}

From source file:despotoski.nikola.github.com.bottomnavigationlayout.BottomTabLayout.java

public int getBackgroundColor() {
    Drawable drawable = getBackground();
    if (drawable instanceof ColorDrawable) {
        ColorDrawable colorDrawable = (ColorDrawable) drawable;
        if (Build.VERSION.SDK_INT >= 11) {
            return colorDrawable.getColor();
        }//from   w  w  w.  j a v  a 2  s  . c o m
        try {
            Field field = colorDrawable.getClass().getDeclaredField("mState");
            field.setAccessible(true);
            Object object = field.get(colorDrawable);
            field = object.getClass().getDeclaredField("mUseColor");
            field.setAccessible(true);
            return field.getInt(object);
        } catch (Exception ignore) {
        }
    }
    return Color.TRANSPARENT;
}

From source file:net.dmulloy2.ultimatearena.types.ArenaZone.java

/**
 * {@inheritDoc}//from  w w w.  j a v a2  s . co  m
 */
@Override
public Map<String, Object> serialize() {
    Map<String, Object> data = new LinkedHashMap<>();

    for (java.lang.reflect.Field field : ArenaZone.class.getDeclaredFields()) {
        if (Modifier.isTransient(field.getModifiers()))
            continue;

        try {
            boolean accessible = field.isAccessible();

            field.setAccessible(true);

            if (field.getType().equals(Integer.TYPE)) {
                if (field.getInt(this) != 0)
                    data.put(field.getName(), field.getInt(this));
            } else if (field.getType().equals(Long.TYPE)) {
                if (field.getLong(this) != 0)
                    data.put(field.getName(), field.getLong(this));
            } else if (field.getType().equals(Boolean.TYPE)) {
                if (field.getBoolean(this))
                    data.put(field.getName(), field.getBoolean(this));
            } else if (field.getType().isAssignableFrom(Collection.class)) {
                if (!((Collection<?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(String.class)) {
                if ((String) field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(Map.class)) {
                if (!((Map<?, ?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else {
                if (field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            }

            field.setAccessible(accessible);
        } catch (Throwable ex) {
        }
    }

    data.put("version", CURRENT_VERSION);
    return data;
}

From source file:com.kkbox.toolkit.app.KKFragment.java

protected void fixStateForNestedFragment() {
    // workaround for sdk < 4.2 Orz
    if (Build.VERSION.SDK_INT < 17) {
        try {//w  w w . j  a  va 2  s.  c o m
            int CREATED = 1; // Created.
            int ACTIVITY_CREATED = 2; // The activity has finished its
            // creation.
            int STOPPED = 3; // Fully created, not started.
            int STARTED = 4; // Created and started, not resumed.
            int RESUMED = 5; // Created started and resumed.
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            Field mState = Fragment.class.getDeclaredField("mState");
            Method dispatchResumeMethod = childFragmentManager.getType().getDeclaredMethod("dispatchResume");
            Method dispatchStartMethod = childFragmentManager.getType().getDeclaredMethod("dispatchStart");
            Method dispatchActivityCreatedMethod = childFragmentManager.getType()
                    .getDeclaredMethod("dispatchActivityCreated");
            Method dispatchCreateMethod = childFragmentManager.getType().getDeclaredMethod("dispatchCreate");
            mState.setAccessible(true);
            childFragmentManager.setAccessible(true);
            int state = mState.getInt(this);
            if (state >= RESUMED) {
                dispatchResumeMethod.invoke(childFragmentManager.get(this));
            } else if (state >= STARTED) {
                dispatchStartMethod.invoke(childFragmentManager.get(this));
            } else if (state >= ACTIVITY_CREATED) {
                dispatchActivityCreatedMethod.invoke(childFragmentManager.get(this));
            } else if (state >= CREATED) {
                dispatchCreateMethod.invoke(childFragmentManager.get(this));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

From source file:com.googlecode.android_scripting.facade.AndroidFacade.java

@Rpc(description = "Get list of constants (static final fields) for a class")
public Bundle getConstants(
        @RpcParameter(name = "classname", description = "Class to get constants from") String classname)
        throws Exception {
    Bundle result = new Bundle();
    int flags = Modifier.FINAL | Modifier.PUBLIC | Modifier.STATIC;
    Class<?> clazz = Class.forName(classname);
    for (Field field : clazz.getFields()) {
        if ((field.getModifiers() & flags) == flags) {
            Class<?> type = field.getType();
            String name = field.getName();
            if (type == int.class) {
                result.putInt(name, field.getInt(null));
            } else if (type == long.class) {
                result.putLong(name, field.getLong(null));
            } else if (type == double.class) {
                result.putDouble(name, field.getDouble(null));
            } else if (type == char.class) {
                result.putChar(name, field.getChar(null));
            } else if (type instanceof Object) {
                result.putString(name, field.get(null).toString());
            }/*from   w w  w . ja v a  2 s .c  o  m*/
        }
    }
    return result;
}

From source file:org.mozilla.gecko.GeckoAppShell.java

public static void showAlertNotification(String aImageUrl, String aAlertTitle, String aAlertText,
        String aAlertCookie, String aAlertName) {
    Log.i(LOGTAG,//from  w  w  w .  ja  v  a  2 s.c  o m
            "GeckoAppShell.showAlertNotification\n" + "- image = '" + aImageUrl + "'\n" + "- title = '"
                    + aAlertTitle + "'\n" + "- text = '" + aAlertText + "'\n" + "- cookie = '" + aAlertCookie
                    + "'\n" + "- name = '" + aAlertName + "'");

    int icon = R.drawable.icon; // Just use the app icon by default

    Uri imageUri = Uri.parse(aImageUrl);
    String scheme = imageUri.getScheme();
    if ("drawable".equals(scheme)) {
        String resource = imageUri.getSchemeSpecificPart();
        resource = resource.substring(resource.lastIndexOf('/') + 1);
        try {
            Class<R.drawable> drawableClass = R.drawable.class;
            Field f = drawableClass.getField(resource);
            icon = f.getInt(null);
        } catch (Exception e) {
        } // just means the resource doesn't exist
        imageUri = null;
    }

    int notificationID = aAlertName.hashCode();

    // Remove the old notification with the same ID, if any
    removeNotification(notificationID);

    AlertNotification notification = new AlertNotification(GeckoApp.mAppContext, notificationID, icon,
            aAlertTitle, aAlertText, System.currentTimeMillis());

    // The intent to launch when the user clicks the expanded notification
    Intent notificationIntent = new Intent(GeckoApp.ACTION_ALERT_CLICK);
    notificationIntent.setClassName(GeckoApp.mAppContext,
            GeckoApp.mAppContext.getPackageName() + ".NotificationHandler");

    // Put the strings into the intent as an URI "alert:<name>#<cookie>"
    Uri dataUri = Uri.fromParts("alert", aAlertName, aAlertCookie);
    notificationIntent.setData(dataUri);

    PendingIntent contentIntent = PendingIntent.getBroadcast(GeckoApp.mAppContext, 0, notificationIntent, 0);
    notification.setLatestEventInfo(GeckoApp.mAppContext, aAlertTitle, aAlertText, contentIntent);
    notification.setCustomIcon(imageUri);
    // The intent to execute when the status entry is deleted by the user with the "Clear All Notifications" button
    Intent clearNotificationIntent = new Intent(GeckoApp.ACTION_ALERT_CLEAR);
    clearNotificationIntent.setClassName(GeckoApp.mAppContext,
            GeckoApp.mAppContext.getPackageName() + ".NotificationHandler");
    clearNotificationIntent.setData(dataUri);
    notification.deleteIntent = PendingIntent.getBroadcast(GeckoApp.mAppContext, 0, clearNotificationIntent, 0);

    mAlertNotifications.put(notificationID, notification);

    notification.show();

    Log.i(LOGTAG, "Created notification ID " + notificationID);
}

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  ww w  . j ava2  s . co 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();
}