Example usage for java.lang.reflect Field getModifiers

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

Introduction

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

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Copies the fields, where the field names are matches.
 *
 * @param <T> the generic type//from ww w .  j  a v  a2  s . co  m
 * @param targetClass the target class
 * @param source the source
 * @param target the target
 * @param fieldNameMatcher the field name matcher
 */
public static <T> void copyInstanceProperties(Class<?> targetClass, T source, T target,
        Matcher<Field> fieldNameMatcher) {
    if (targetClass == null) {
        return;
    }

    for (Field f : targetClass.getDeclaredFields()) {
        int mod = f.getModifiers();
        if (Modifier.isStatic(mod) == true) {
            continue;
        }
        if (fieldNameMatcher.match(f) == false) {
            continue;
        }
        Object value = readField(source, f.getName());
        writeField(target, f, value);
    }
    copyInstanceProperties(targetClass.getSuperclass(), source, target, fieldNameMatcher);
}

From source file:Base64.java

/**
 * Draws a line on the screen at the specified index. Default is green.
 * <p/>//from   ww w . j ava  2 s  .c om
 * Available colours: red, green, cyan, purple, white.
 *
 * @param render The Graphics object to be used.
 * @param row    The index where you want the text.
 * @param text   The text you want to render. Colours can be set like [red].
 */
public static void drawLine(Graphics render, int row, String text) {
    FontMetrics metrics = render.getFontMetrics();
    int height = metrics.getHeight() + 4; // height + gap
    int y = row * height + 15 + 19;
    String[] texts = text.split("\\[");
    int xIdx = 7;
    Color cur = Color.GREEN;
    for (String t : texts) {
        for (@SuppressWarnings("unused")
        String element : COLOURS_STR) {
            // String element = COLOURS_STR[i];
            // Don't search for a starting '[' cause it they don't exists.
            // we split on that.
            int endIdx = t.indexOf(']');
            if (endIdx != -1) {
                String colorName = t.substring(0, endIdx);
                if (COLOR_MAP.containsKey(colorName)) {
                    cur = COLOR_MAP.get(colorName);
                } else {
                    try {
                        Field f = Color.class.getField(colorName);
                        int mods = f.getModifiers();
                        if (Modifier.isPublic(mods) && Modifier.isStatic(mods) && Modifier.isFinal(mods)) {
                            cur = (Color) f.get(null);
                            COLOR_MAP.put(colorName, cur);
                        }
                    } catch (Exception ignored) {
                    }
                }
                t = t.replace(colorName + "]", "");
            }
        }
        render.setColor(Color.BLACK);
        render.drawString(t, xIdx, y + 1);
        render.setColor(cur);
        render.drawString(t, xIdx, y);
        xIdx += metrics.stringWidth(t);
    }
}

From source file:springfox.documentation.spring.web.readers.parameter.ModelAttributeParameterExpander.java

private Predicate<Field> staticField() {
    return new Predicate<Field>() {
        @Override/*  w  ww. java  2s  . co m*/
        public boolean apply(Field input) {
            return isStatic(input.getModifiers());
        }
    };
}

From source file:com.tlabs.android.evanova.mvp.PresenterLifeCycle.java

private void addAnnotatedPresenter(Object source) {
    for (Field field : source.getClass().getDeclaredFields()) {
        if (field.isAnnotationPresent(Presenter.class)) {
            if (Modifier.isPrivate(field.getModifiers())) {
                throw new NotAccessibleException("presenter on " + field.getName() + " canot be private");
            } else {
                try {
                    field.setAccessible(true);
                    ViewPresenter presenter = (ViewPresenter) field.get(source);
                    registerPresenter(presenter);
                    field.setAccessible(false);
                } catch (IllegalAccessException e) {
                    NotAccessibleException exception = new NotAccessibleException(field.getName(), e);
                    throw exception;
                }/*from w w w  .j  a  v  a 2s. c  o m*/
            }
        }
    }
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find nested implementing./*from   w w  w .  ja  v a 2s . com*/
 *
 * @param <T> the generic type
 * @param bean the bean
 * @param clazz the clazz
 * @param iface the iface
 * @param result the result
 * @param depth the depth
 * @param includeStatics the include statics
 */
@SuppressWarnings("unchecked")
public static <T> void findNestedImplementing(Object bean, Class<?> clazz, Class<T> iface, List<T> result,
        int depth, boolean includeStatics) {
    if (iface.isAssignableFrom(clazz) == true) {
        result.add((T) bean);
    }
    if (depth == 0) {
        return;
    }

    for (Field f : clazz.getDeclaredFields()) {
        if (includeStatics == false && (f.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
            continue;
        }
        Object o = readField(bean, f);
        findNestedImplementing(o, iface, result, depth - 1, includeStatics);
    }
    if (clazz == Object.class || clazz.getSuperclass() == null) {
        return;
    }
    findNestedImplementing(bean, clazz.getSuperclass(), iface, result, depth, includeStatics);
}

From source file:com.uphyca.testing.junit3.support.v4.FragmentTestCase.java

/**
 * This function is called by various TestCase implementations, at
 * tearDown() time, in order to scrub out any class variables. This protects
 * against memory leaks in the case where a test case creates a non-static
 * inner class (thus referencing the test case) and gives it to someone else
 * to hold onto./*  w ww.  j a  v a2 s.  c  o m*/
 * 
 * @param testCaseClass
 *            The class of the derived TestCase implementation.
 * 
 * @throws IllegalAccessException
 */
protected void scrubClass(final Class<?> testCaseClass) throws IllegalAccessException {
    final Field[] fields = getClass().getDeclaredFields();
    for (Field field : fields) {
        final Class<?> fieldClass = field.getDeclaringClass();
        if (testCaseClass.isAssignableFrom(fieldClass) && !field.getType().isPrimitive()
                && (field.getModifiers() & Modifier.FINAL) == 0) {
            try {
                field.setAccessible(true);
                field.set(this, null);
            } catch (Exception e) {
                android.util.Log.d("TestCase", "Error: Could not nullify field!");
            }

            if (field.get(this) != null) {
                android.util.Log.d("TestCase", "Error: Could not nullify field!");
            }
        }
    }
}

From source file:py.una.pol.karaku.dao.entity.interceptors.InterceptorHandler.java

/**
 * Verifica si un field puede ser asignable. Se define un fiel asignable
 * como aquel que no es estatico, final.
 * //from   w w  w .  jav a 2 s.c o m
 * Como nota general tener en cuenta que un campo que no es String es
 * inmediatamente no asignable
 * 
 * @param field
 *            a ser evaluado
 * @return <code>true</code> si es asignable, <code>false</code> en caso
 *         contrario
 */
private boolean isAssignable(Field field) {

    int modifier = field.getModifiers();
    if (Modifier.isFinal(modifier)) {
        return false;
    }
    if (Modifier.isStatic(modifier)) {
        return false;
    }
    if (Modifier.isTransient(modifier)) {
        return false;
    }
    return field.getAnnotation(Transient.class) == null;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudInvocationInfoDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudInvocationInfos.class) != null) {

            Type[] genericTypes = ((ParameterizedType) f.getGenericType()).getActualTypeArguments();
            Class<?> typeParameter = (Class<?>) genericTypes[0];

            if (!f.getType().equals(List.class) || genericTypes.length != 1
                    || !typeParameter.equals(InvocationInfo.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudInvocationInfos. You may only annotate java.util.List<InvocationInfo> fields.");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudInvocationInfos. " + "Field has to be non-static.");

        }//from w w  w.  jav  a 2  s. c om
    }

}

From source file:net.redwarp.library.database.TableInfo.java

@SuppressWarnings("unchecked")
private TableInfo(Class<T> c) {
    mClass = c;/*  w  w w  .j av a  2  s.com*/

    if (c.isAnnotationPresent(Version.class)) {
        final Version version = c.getAnnotation(Version.class);
        mVersion = version.value();
    } else {
        mVersion = 1;
    }

    Field[] fields = mClass.getDeclaredFields();
    //        mFieldMap = new HashMap<>(fields.length);
    mColumns = new HashMap<>(fields.length);
    mObjectFields = new ArrayList<>();

    List<String> columnNames = new ArrayList<>(fields.length);
    List<Field> finalFields = new ArrayList<>(fields.length);
    List<Field> chainDeleteFields = new ArrayList<>(fields.length);

    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            SQLiteUtils.SQLiteType type = SQLiteUtils.getSqlLiteTypeForField(field);
            if (type != null) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(PrimaryKey.class)) {
                    if (primaryKey != null) {
                        throw new RuntimeException("There can be only one primary key");
                    }
                    final PrimaryKey primaryKeyAnnotation = field.getAnnotation(PrimaryKey.class);
                    String name = primaryKeyAnnotation.name();
                    if ("".equals(name)) {
                        name = getColumnName(field);
                    }
                    columnNames.add(name);
                    primaryKey = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                } else {
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    mColumns.put(field, new Column(name, field, type));
                }

                finalFields.add(field);
            } else {
                // Not a basic field;
                if (field.isAnnotationPresent(Chain.class)) {
                    // We must serialize/unserialize this as well
                    final Chain chainAnnotation = field.getAnnotation(Chain.class);
                    if (chainAnnotation.delete()) {
                        chainDeleteFields.add(field);
                    }
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    Column column = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                    mColumns.put(field, column);
                    mObjectFields.add(field);
                    finalFields.add(field);
                }
            }
        }
    }
    mColumnNames = columnNames.toArray(new String[columnNames.size()]);
    mFields = finalFields.toArray(new Field[finalFields.size()]);
    mChainDeleteFields = chainDeleteFields.toArray(new Field[chainDeleteFields.size()]);
}

From source file:com.yek.keyboard.ChewbaccaUncaughtExceptionHandler.java

private void addResourceNameWithId(StringBuilder resources, int resourceId, Class clazz) {
    for (Field field : clazz.getFields()) {
        if (field.getType().equals(int.class)) {
            if ((field.getModifiers() & (Modifier.STATIC | Modifier.PUBLIC)) != 0) {
                try {
                    if (resourceId == field.getInt(null)) {
                        resources.append(clazz.getName()).append(".").append(field.getName());
                        resources.append('\n');
                    }/*from  ww  w . j  a  v a2 s  . c o  m*/
                } catch (IllegalAccessException e) {
                    Logger.d("EEEE", "Failed to access " + field.getName(), e);
                }
            }
        }
    }
}