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:run.ace.Utils.java

public static void setField(Class c, Object instance, String fieldName, Object fieldValue) {
    try {//w ww  .j  a v a  2 s .co m
        Field f = c.getField(fieldName);
        f.set(instance, fieldValue);
    } catch (NoSuchFieldException ex) {
        throw new RuntimeException(c.getSimpleName() + " does not have a matching " + fieldName + " field");
    } catch (IllegalAccessException ex) {
        throw new RuntimeException(c.getSimpleName() + "'s " + fieldName + " field is inaccessible");
    }
}

From source file:Main.java

public static int getIdByName(Context context, String className, String name) {
    String packageName = context.getPackageName();
    Class r = null;//from   w  w w .  j  a  v  a2s . c  o m
    int id = 0;
    try {
        r = Class.forName(packageName + ".R");

        Class[] classes = r.getClasses();
        Class desireClass = null;

        for (int i = 0; i < classes.length; ++i) {
            if (classes[i].getName().split("\\$")[1].equals(className)) {
                desireClass = classes[i];
                break;
            }
        }
        if (classes.length == 0) {
            desireClass = Class.forName(packageName + ".R$" + className);
        }
        if (desireClass != null)
            id = desireClass.getField(name).getInt(desireClass);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (SecurityException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }

    return id;
}

From source file:com.eurelis.opencms.workflows.moduleconfiguration.ModuleConfigurationLoader.java

/**
 * Load the config file, extract value/*w  w w  . j a  v a 2 s.  c  om*/
 * 
 * @param instance
 *            the instance to update
 * @throws IOException
 *             if a problem occurs during initialization
 */
private static void loadConfigFile(ModuleConfiguration instance) throws IOException {
    CmsResource resource = OpenCmsEasyAccess.getResource(CONFIG_FILE);

    if (resource != null) {
        if (resource.isFile()) {
            // Read the file
            byte[] fileContent = OpenCmsEasyAccess.readFile(resource);

            if (fileContent.length > 0) {

                // get a reader on the file
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(new ByteArrayInputStream(fileContent)));

                /*
                 * Read all lines of the files
                 */
                String readLine = null;
                while ((readLine = reader.readLine()) != null) {

                    //remove useless space and other
                    readLine = readLine.trim();

                    // ignore line starting with "#" or emptyline
                    if (!readLine.startsWith(COMMENT_STRING) && !readLine.equals("")) {

                        String[] configValues = readLine.split(SEPARATOR_STRING);
                        if (configValues.length > 1) {
                            Class moduleConfigurationClass = instance.getClass();
                            if (moduleConfigurationClass != null) {
                                try {
                                    //set the new value
                                    Field fieldToFill = moduleConfigurationClass
                                            .getField(configValues[0].trim());
                                    if (fieldToFill != null) {
                                        try {
                                            fieldToFill.set(instance, configValues[1].trim());
                                        } catch (IllegalArgumentException e) {
                                            LOGGER.info(ErrorFormatter.formatException(e));
                                        } catch (IllegalAccessException e) {
                                            LOGGER.info(ErrorFormatter.formatException(e));
                                        }
                                    } else {
                                        LOGGER.debug("No field associated to " + configValues[0]
                                                + " has been found");
                                    }

                                } catch (SecurityException e) {
                                    LOGGER.info(ErrorFormatter.formatException(e));
                                } catch (NoSuchFieldException e) {
                                    LOGGER.info(ErrorFormatter.formatException(e));
                                }
                            } else {
                                LOGGER.debug("The class of ModuleConfiguration instance has not been found !");
                            }
                        } else {
                            LOGGER.info("The line " + readLine + " doesn't correspond to a valid property");
                        }

                    }
                }

            } else {
                LOGGER.warn("The config file " + CONFIG_FILE + " is empty.");
            }
        } else {
            LOGGER.warn("The config file " + CONFIG_FILE + " is not a file.");
        }

    } else {
        LOGGER.warn("The config file " + CONFIG_FILE + " has not been found.");
    }

    //LOGGER.debug("WF | instance = "+instance);
}

From source file:com.cardvlaue.sys.util.ScreenUtil.java

/**
 * ?????MIUI 6?//w ww .j  a v a2  s.  com
 */
public static void setStatusBarDarkMode(boolean darkmode, Activity activity) {
    Class<? extends Window> clazz = activity.getWindow().getClass();
    try {
        int darkModeFlag = 0;
        Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
        Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
        darkModeFlag = field.getInt(layoutParams);
        Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
        extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
    } catch (Exception e) {
        // e.printStackTrace();
    }
}

From source file:org.eclipse.wb.internal.xwt.model.property.editor.style.StylePropertyEditor.java

private static Field getField(EditorContext context, Class<?> baseClass, String name) {
    try {//w  ww  . ja  va 2 s.c  o m
        return baseClass.getField(name);
    } catch (NoSuchFieldException e) {
        context.addWarning(new EditorWarning(
                "StylePropertyEditor: can not find field " + baseClass.getName() + "." + name, e));
        return null;
    }
}

From source file:ReflectUtil.java

/**
 * Looks for an instance (i.e. non-static) public field with the matching name and
 * returns it if one exists.  If no such field exists, returns null.
 *
 * @param clazz the clazz who's fields to examine
 * @param property the name of the property/field to look for
 * @return the Field object or null if no matching field exists
 *///from w  w w .  j a  v  a  2s . c o m
public static Field getField(Class<?> clazz, String property) {
    try {
        Field field = clazz.getField(property);
        return !Modifier.isStatic(field.getModifiers()) ? field : null;
    } catch (NoSuchFieldException nsfe) {
        return null;
    }
}

From source file:org.eclipse.xtend.typesystem.emf.EcoreUtil2.java

/**
 * Finds an EPackage by the class name of the Package Descriptor.
 * /*from   w  ww .  j  a  v  a 2  s  .c o  m*/
 * @param ePackageDescriptor
 *            The Package Descriptor's classname
 * @return The EPackage instance. Returns <code>null</code> on any exception
 *         occuring while retrieval.
 */
public static EPackage getEPackageByDescriptorClassName(final String ePackageDescriptor) {
    Class clazz;
    try {
        clazz = ResourceLoaderFactory.createResourceLoader().loadClass(ePackageDescriptor);
        final EPackage.Descriptor descriptor = (EPackage.Descriptor) clazz.newInstance();
        final Field f = clazz.getField("eNS_URI");
        final String uri = (String) f.get(null);
        EPackage.Registry.INSTANCE.put(uri, descriptor);
        return EPackage.Registry.INSTANCE.getEPackage(uri);
    } catch (final Exception e) {
        log.error("Couldn't load ePackage '" + ePackageDescriptor, e);
        return null;
    } finally {
        logPackages();
    }
}

From source file:Main.java

public static <T> T getObjInList(Class<T> clazz, Collection<T> all, String valueStr, String propName)
        throws Exception {
    if (all.isEmpty() || valueStr == null) {
        return null;
    }/*from  w  w w.j ava 2s.  co m*/
    T obj = null;
    Iterator<T> iter = all.iterator();
    for (; iter.hasNext();) {
        T temp = iter.next();
        Object match = null;
        if (propName == null) {
            match = temp.toString();
        } else {
            Field field = clazz.getField(propName);
            field.setAccessible(true);
            match = field.get(temp);
        }
        if (valueStr.equals(match)) {
            obj = temp;
            break;
        }
    }
    return obj;
}

From source file:ar.com.zauber.commons.repository.BaseEntity.java

/**
 * @param theClass//from w ww  .  j ava  2  s  .  co  m
 * @return
 */
private static Set<Field> getIdentityFields(final Class<?> theClass) {
    Set<Field> fields = new HashSet<Field>();
    if (theClass.getAnnotation(IdentityProperties.class) != null) {
        String[] fieldNamesArray = theClass.getClass().getAnnotation(IdentityProperties.class).fieldNames();
        for (int i = 0; i < fieldNamesArray.length; i++) {
            try {
                fields.add((theClass.getField(fieldNamesArray[i])));
            } catch (final SecurityException e) {
                throw new IllegalStateException(e);
            } catch (final NoSuchFieldException e) {
                throw new IllegalStateException(e);
            }

        }
    } else {
        Field[] fieldsArray = theClass.getFields();
        for (int i = 0; i < fieldsArray.length; i++) {
            if (fieldsArray[i].getAnnotation(IdentityProperty.class) != null) {
                fields.add(fieldsArray[i]);
            }
        }
        if (!theClass.getSuperclass().equals(Object.class)) {
            fields.addAll(getIdentityFields(theClass.getSuperclass()));
        }
    }
    return fields;
}

From source file:Main.java

private static int getStatusBarHeight(Activity activity) {
    Class<?> c;
    Object obj;//from w  w w  . ja  v a 2s  .c o m
    Field field;
    int x;
    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 = activity.getResources().getDimensionPixelSize(x);
    } catch (Exception e1) {
        e1.printStackTrace();
    }
    return statusBarHeight;
}