Example usage for java.lang.reflect Field getLong

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

Introduction

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

Prototype

@CallerSensitive
@ForceInline 
public long getLong(Object obj) throws IllegalArgumentException, IllegalAccessException 

Source Link

Document

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

Usage

From source file:org.pkcs11.jacknji11.C.java

/**
 * Helper method.  Adds all public static final long fields in c to map, mapping field value to name.
 * @param c class/*from  w w  w.  jav a  2  s. c o m*/
 * @return map of field value:name
 */
public static Map<Long, String> createL2SMap(Class<?> c) {
    Map<Long, String> map = new HashMap<Long, String>();
    try {
        for (Field f : c.getDeclaredFields()) {
            // only put 'public static final long' in map
            if (f.getType() == long.class && Modifier.isPublic(f.getModifiers())
                    && Modifier.isStatic(f.getModifiers()) && Modifier.isFinal(f.getModifiers())) {
                map.put(f.getLong(null), f.getName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return map;
}

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

@Override
public Map<String, Object> serialize() {
    Map<String, Object> data = new LinkedHashMap<>();

    for (Field field : ArenaConfig.class.getDeclaredFields()) {
        try {/*from www . j  a  v a2 s . c om*/
            if (Modifier.isTransient(field.getModifiers()))
                continue;

            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) {
        }
    }

    serializeCustomOptions(data);
    return data;
}

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

@SuppressWarnings("rawtypes")
public SwitchLayout(Context context) {
    mContext = context;//  w  ww  .  jav  a  2 s. c  o m
    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:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory().//from w  w  w . j av  a  2s .c  o m
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance");
            Object object = method.invoke(null);

            File file = new File(current, clazz.getName() + ".ser");
            boolean created = file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        @SuppressWarnings("Convert2Diamond")
        List<String> fieldList = new ArrayList<>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", e);
    }
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Serializes the given class to the getCurrentDirectory() directory. The
 * static serializedInstance() method of clazz will be called to get an
 * examplar of clazz. This examplar will then be serialized out to a file
 * stored in getCurrentDirectory()./* w w w.  jav  a 2s. c om*/
 *
 * @param clazz the class to serialize.
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getCurrentDirectory()
 */
private void serializeClass(Class clazz, Map<String, List<String>> classFields) throws RuntimeException {
    File current = new File(getCurrentDirectory());

    if (!current.exists() || !current.isDirectory()) {
        throw new IllegalStateException("There is no " + current.getAbsolutePath() + " directory. "
                + "\nThis is where the serialized classes should be. "
                + "Please run serializeCurrentDirectory() first.");
    }

    try {
        Field field = clazz.getDeclaredField("serialVersionUID");

        int modifiers = field.getModifiers();
        boolean _static = Modifier.isStatic(modifiers);
        boolean _final = Modifier.isFinal(modifiers);
        field.setAccessible(true);

        if (!_static || !_final || !(23L == field.getLong(null))) {
            throw new RuntimeException(
                    "Class " + clazz + " does not define static final " + "long serialVersionUID = 23L");
        }

        int numFields = getNumNonSerialVersionUIDFields(clazz);

        if (numFields > 0) {
            Method method = clazz.getMethod("serializableInstance", new Class[0]);
            Object object = method.invoke(null, new Object[0]);

            File file = new File(current, clazz.getName() + ".ser");
            file.createNewFile();

            FileOutputStream out = new FileOutputStream(file);
            ObjectOutputStream objOut = new ObjectOutputStream(out);
            objOut.writeObject(object);
            out.close();
        }

        // Make entry in list of class fields.
        ObjectStreamClass objectStreamClass = ObjectStreamClass.lookup(clazz);
        String className = objectStreamClass.getName();
        ObjectStreamField[] fields = objectStreamClass.getFields();
        List<String> fieldList = new ArrayList<String>();

        for (ObjectStreamField objectStreamField : fields) {
            String fieldName = objectStreamField.getName();
            fieldList.add(fieldName);
        }

        classFields.put(className, fieldList);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(("There is no static final long field " + "'serialVersionUID' in " + clazz
                + ". Please make one and set it " + "to 23L."));
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(
                "Class " + clazz + "does not " + "have a public static serializableInstance constructor.", e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(
                "The method serializableInstance() of " + "class " + clazz + " is not public.", e);
    } catch (InvocationTargetException e) {
        throw new RuntimeException(
                "Unable to statically call the " + "serializableInstance() method of class " + clazz + ".", e);
    } catch (IOException e) {
        throw new RuntimeException("Could not create a new, writeable file " + "in " + getCurrentDirectory()
                + " when trying to serialize " + clazz + ".", 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   ww  w. java  2s  . com
        }
    }
    return result;
}

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

/**
 * {@inheritDoc}/*from w  ww.  j  ava2s  .  c  om*/
 */
@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.nonninz.robomodel.RoboModel.java

void saveField(Field field, TypedContentValues cv) {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    field.setAccessible(true);//  ww w  .j a  v a 2  s  .  c om

    try {
        if (type == String.class) {
            cv.put(field.getName(), (String) field.get(this));
        } else if (type == Boolean.TYPE) {
            cv.put(field.getName(), field.getBoolean(this));
        } else if (type == Byte.TYPE) {
            cv.put(field.getName(), field.getByte(this));
        } else if (type == Double.TYPE) {
            cv.put(field.getName(), field.getDouble(this));
        } else if (type == Float.TYPE) {
            cv.put(field.getName(), field.getFloat(this));
        } else if (type == Integer.TYPE) {
            cv.put(field.getName(), field.getInt(this));
        } else if (type == Long.TYPE) {
            cv.put(field.getName(), field.getLong(this));
        } else if (type == Short.TYPE) {
            cv.put(field.getName(), field.getShort(this));
        } else if (type.isEnum()) {
            final Object value = field.get(this);
            if (value != null) {
                final Method method = type.getMethod("name");
                final String str = (String) method.invoke(value);
                cv.put(field.getName(), str);
            }
        } else {
            // Try to JSONify it (db column must be of type text)
            final String json = mMapper.writeValueAsString(field.get(this));
            cv.put(field.getName(), json);
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final JsonProcessingException e) {
        Ln.w(e, "Error while dumping %s of type %s to Json", field.getName(), type);
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

From source file:org.slc.sli.api.service.BasicServiceTest.java

@SuppressWarnings("unchecked")
@Test/*ww  w. j  ava 2  s  .  c o m*/
public void testGetAccessibleEntitiesCountLimit() throws SecurityException, NoSuchFieldException,
        IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    securityContextInjector.setDualContext();
    SecurityUtil.setUserContext(SecurityUtil.UserContext.DUAL_CONTEXT);

    List<Entity> entities = new ArrayList<Entity>();
    Map<String, SecurityUtil.UserContext> studentContext = new HashMap<String, SecurityUtil.UserContext>();
    for (int i = 0; i < 30; i++) {
        String id = "student" + i;
        entities.add(
                new MongoEntity("student", id, new HashMap<String, Object>(), new HashMap<String, Object>()));
        studentContext.put(id, SecurityUtil.UserContext.DUAL_CONTEXT);
    }

    Mockito.when(mockRepo.findAll(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(entities);
    Mockito.when(mockRepo.count(Mockito.eq("student"), Mockito.any(NeutralQuery.class))).thenReturn(50L);

    ContextValidator mockContextValidator = Mockito.mock(ContextValidator.class);
    Field contextValidator = BasicService.class.getDeclaredField("contextValidator");
    contextValidator.setAccessible(true);
    contextValidator.set(service, mockContextValidator);
    Mockito.when(mockContextValidator.getValidatedEntityContexts(Matchers.any(EntityDefinition.class),
            Matchers.any(Collection.class), Matchers.anyBoolean(), Matchers.anyBoolean()))
            .thenReturn(studentContext);

    RightAccessValidator mockAccessValidator = Mockito.mock(RightAccessValidator.class);
    Field rightAccessValidator = BasicService.class.getDeclaredField("rightAccessValidator");
    rightAccessValidator.setAccessible(true);
    rightAccessValidator.set(service, mockAccessValidator);
    Mockito.when(mockAccessValidator.getContextualAuthorities(Matchers.anyBoolean(), Matchers.any(Entity.class),
            Matchers.eq(SecurityUtil.UserContext.DUAL_CONTEXT), Matchers.anyBoolean()))
            .thenReturn(new HashSet<GrantedAuthority>());
    Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkAccess(Mockito.anyBoolean(),
            Mockito.anyBoolean(), Mockito.argThat(new MatchesNotAccessible()), Mockito.anyString(),
            Mockito.anyCollection());
    Mockito.doThrow(new AccessDeniedException("")).when(mockAccessValidator).checkFieldAccess(
            Mockito.any(NeutralQuery.class), Mockito.argThat(new MatchesNotFieldAccessible()),
            Mockito.anyString(), Mockito.anyCollection());

    NeutralQuery query = new NeutralQuery();
    query.setLimit(MAX_RESULT_SIZE);

    final long mockCountLimit = 5;
    Field countLimit = BasicService.class.getDeclaredField("countLimit");
    countLimit.setAccessible(true);
    final long prevCountLimit = countLimit.getLong(service);
    countLimit.set(service, mockCountLimit);

    Method method = BasicService.class.getDeclaredMethod("getResponseEntities", NeutralQuery.class,
            boolean.class);
    method.setAccessible(true);

    RequestUtil.setCurrentRequestId();
    Collection<Entity> accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);

    Iterable<String> expectedResult1 = Arrays.asList("student2", "student4", "student5", "student6",
            "student13");
    assertEntityIdsEqual(expectedResult1.iterator(), accessibleEntities.iterator());

    long count = service.getAccessibleEntitiesCount("student");
    Assert.assertEquals(5, count);

    // Assure same order and count.

    RequestUtil.setCurrentRequestId();

    accessibleEntities = (Collection<Entity>) method.invoke(service, query, false);

    Iterable<String> expectedResult2 = Arrays.asList("student2", "student4", "student5", "student6",
            "student13");
    assertEntityIdsEqual(expectedResult2.iterator(), accessibleEntities.iterator());

    count = service.getAccessibleEntitiesCount("student");
    Assert.assertEquals(5, count);

    countLimit.set(service, prevCountLimit);
}

From source file:la2launcher.MainFrame.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed

    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
    int srow = jTable1.getSelectedRow();
    if (srow < 0) {
        return;//from   ww  w.  j a va 2s.c  o m
    }
    Integer procid = (Integer) dtm.getValueAt(srow, 0);
    for (Process proc : procs) {
        if ((proc.hashCode() + "").equals(procid.toString())) {
            try {
                Field field = proc.getClass().getDeclaredField("handle");
                if (!field.isAccessible()) {
                    field.setAccessible(true);
                }
                long pid = field.getLong(proc);

                Kernel32 kernel = Kernel32.INSTANCE;
                W32API.HANDLE handle = new W32API.HANDLE();
                handle.setPointer(Pointer.createConstant(pid));
                long pid_ = kernel.GetProcessId(handle);

                User32 u32 = User32.INSTANCE;
                u32.EnumWindows(new WinUser.WNDENUMPROC() {
                    @Override
                    public boolean callback(WinDef.HWND hwnd, Pointer pntr) {
                        char[] windowText = new char[512];
                        u32.GetWindowText(hwnd, windowText, 512);
                        String wText = Native.toString(windowText);

                        if (wText.isEmpty()) {
                            return true;
                        }

                        if (wText.equals("Lineage II")) { //TODO: 111
                            IntByReference pid__ = new IntByReference();
                            u32.GetWindowThreadProcessId(hwnd, pid__);
                            if ((pid__.getValue() + "").equals(pid_ + "")) {
                                u32.SetForegroundWindow(hwnd);
                                lastHWND = hwnd;
                            }
                        }
                        return true;
                    }
                }, null);
            } catch (NoSuchFieldException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SecurityException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalArgumentException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

}