Example usage for java.lang.reflect Modifier isFinal

List of usage examples for java.lang.reflect Modifier isFinal

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isFinal.

Prototype

public static boolean isFinal(int mod) 

Source Link

Document

Return true if the integer argument includes the final modifier, false otherwise.

Usage

From source file:org.eclipse.smarthome.config.core.internal.ConfigMapper.java

/**
 * Use this method to automatically map a configuration collection to a Configuration holder object. A common
 * use-case would be within a service. Usage example:
 *
 * <pre>/*from w  w  w.  j  a  va  2 s .co m*/
 * {@code
 *   public void modified(Map<String, Object> properties) {
 *     YourConfig config = ConfigMapper.as(properties, YourConfig.class);
 *   }
 * }
 * </pre>
 *
 *
 * @param properties The configuration map.
 * @param configurationClass The configuration holder class. An instance of this will be created so make sure that
 *            a default constructor is available.
 * @return The configuration holder object. All fields that matched a configuration option are set. If a required
 *         field is not set, null is returned.
 */
public static <T> @Nullable T as(Map<String, Object> properties, Class<T> configurationClass) {
    T configuration = null;
    try {
        configuration = configurationClass.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        return null;
    }

    List<Field> fields = getAllFields(configurationClass);
    for (Field field : fields) {
        // Don't try to write to final fields and ignore transient fields
        if (Modifier.isFinal(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
            continue;
        }
        String fieldName = field.getName();
        String configKey = fieldName;
        Class<?> type = field.getType();

        Object value = properties.get(configKey);

        // Consider RequiredField annotations
        if (value == null) {
            logger.trace("Skipping field '{}', because config has no entry for {}", fieldName, configKey);
            continue;
        }

        // Allows to have List<int>, List<Double>, List<String> etc
        if (value instanceof Collection) {
            Collection<?> c = (Collection<?>) value;
            Class<?> innerClass = (Class<?>) ((ParameterizedType) field.getGenericType())
                    .getActualTypeArguments()[0];
            final List<Object> lst = new ArrayList<>(c.size());
            for (final Object it : c) {
                final Object normalized = objectConvert(it, innerClass);
                lst.add(normalized);
            }
            value = lst;
        }

        try {
            value = objectConvert(value, type);
            logger.trace("Setting value ({}) {} to field '{}' in configuration class {}", type.getSimpleName(),
                    value, fieldName, configurationClass.getName());
            FieldUtils.writeField(configuration, fieldName, value, true);

        } catch (Exception ex) {
            logger.warn("Could not set field value for field '{}': {}", fieldName, ex.getMessage(), ex);
        }
    }

    return configuration;
}

From source file:name.ikysil.beanpathdsl.dynamic.DynamicBeanPath.java

/**
 * Continue bean path construction from a bean of specified class.
 *
 * @param <T> type of the bean//from   w  ww . j  av a 2  s.c  o  m
 * @param clazz class of the bean
 * @return instance of the bean class instrumented to capture getters and setters invocations
 */
@SuppressWarnings("unchecked")
public static <T> T expr(Class<T> clazz) {
    try {
        T result;
        if (Modifier.isFinal(clazz.getModifiers())) {
            result = clazz.newInstance();
        } else {
            ProxyFactory pf = new ProxyFactory();
            if (clazz.isInterface()) {
                pf.setSuperclass(Object.class);
                pf.setInterfaces(new Class<?>[] { clazz });
            } else {
                pf.setSuperclass(clazz);
            }
            pf.setFilter(new DefaultMethodFilter());
            result = (T) pf.create(new Class<?>[0], new Object[0], new DefaultMethodHandler(clazz));
        }
        return result;
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | IllegalArgumentException
            | InvocationTargetException ex) {
        throw new IllegalStateException(String.format("Can't instantiate %s", clazz.getName()), ex);
    }
}

From source file:org.force66.vobase.ValueObjectBaseTest.java

@Before
public void setUp() throws Exception {
    ValueGeneratorFactory valueFactory = new ValueGeneratorFactory();
    populatedVO = new TestVO();

    for (Field field : TestVO.class.getDeclaredFields()) {
        if (!Modifier.isFinal(field.getModifiers())) {
            ValueGenerator valueGen = valueFactory.forClass(field.getType());
            if (valueGen != null) {
                FieldUtils.writeField(field, populatedVO, valueGen.makeValues()[0], true);
            }/*from   w ww . j av a 2 s  .  c o  m*/
        }
    }
}

From source file:com.activecq.api.ActiveProperties.java

/**
 * Uses reflection to create a List of the keys defined in the ActiveField subclass (and its inheritance tree).
 * Only fields that meet the following criteria are returned:
 * - public//from   ww w. j a  v a 2 s .  c o  m
 * - static
 * - final
 * - String
 * - Upper case 
 * @return a List of all the Fields
 */
@SuppressWarnings("unchecked")
public List<String> getKeys() {
    ArrayList<String> keys = new ArrayList<String>();
    ArrayList<String> names = new ArrayList<String>();
    Class cls = this.getClass();

    if (cls == null) {
        return Collections.unmodifiableList(keys);
    }

    Field fieldList[] = cls.getFields();

    for (Field fld : fieldList) {
        int mod = fld.getModifiers();

        // Only look at public static final fields
        if (!Modifier.isPublic(mod) || !Modifier.isStatic(mod) || !Modifier.isFinal(mod)) {
            continue;
        }

        // Only look at String fields
        if (!String.class.equals(fld.getType())) {
            continue;
        }

        // Only look at uppercase fields
        if (!StringUtils.equals(fld.getName().toUpperCase(), fld.getName())) {
            continue;
        }

        // Get the value of the field
        String value;
        try {
            value = StringUtils.stripToNull((String) fld.get(this));
        } catch (IllegalArgumentException e) {
            continue;
        } catch (IllegalAccessException e) {
            continue;
        }

        // Do not add duplicate or null keys, or previously added named fields
        if (value == null || names.contains(fld.getName()) || keys.contains(value)) {
            continue;
        }

        // Success! Add key to key list
        keys.add(value);

        // Add field named to process field names list
        names.add(fld.getName());

    }

    return Collections.unmodifiableList(keys);
}

From source file:org.apache.hadoop.fs.TestFilterFs.java

public void testFilterFileSystem() throws Exception {
    for (Method m : AbstractFileSystem.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()))
            continue;
        if (Modifier.isPrivate(m.getModifiers()))
            continue;
        if (Modifier.isFinal(m.getModifiers()))
            continue;

        try {//from   w w w .ja  v  a  2 s  . co m
            DontCheck.class.getMethod(m.getName(), m.getParameterTypes());
            LOG.info("Skipping " + m);
        } catch (NoSuchMethodException exc) {
            LOG.info("Testing " + m);
            try {
                FilterFs.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
            } catch (NoSuchMethodException exc2) {
                LOG.error("FilterFileSystem doesn't implement " + m);
                throw exc2;
            }
        }
    }
}

From source file:org.eclipse.wb.internal.core.model.description.rules.PublicFieldPropertiesRule.java

@Override
public void begin(String namespace, String name, Attributes attributes) throws Exception {
    ComponentDescription componentDescription = (ComponentDescription) digester.peek();
    Class<?> componentClass = componentDescription.getComponentClass();
    for (Field field : componentClass.getFields()) {
        int modifiers = field.getModifiers();
        if (!Modifier.isStatic(modifiers) && !Modifier.isFinal(modifiers)) {
            addSingleProperty(componentDescription, field);
        }/*  www .ja v a  2 s .  co m*/
    }
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Returns 1 if the type is a collection,
 * -1 if it is definitely not//w w  w  .j  a  v a  2 s . c o  m
 * and 0 if it may be a collection in some cases.
 * @param clazz to test
 * @return int
 */
public static int getCollectionHint(Class clazz) {
    if (clazz.isArray()) {
        return 1;
    }

    if (Collection.class.isAssignableFrom(clazz)) {
        return 1;
    }

    if (clazz.isPrimitive()) {
        return -1;
    }

    if (clazz.isInterface()) {
        return 0;
    }

    if (Modifier.isFinal(clazz.getModifiers())) {
        return -1;
    }

    return 0;
}

From source file:com.sjsu.crawler.util.RandomStringUtilsTest.java

@Test
public void testConstructor() {
    assertNotNull(new RandomStringUtils());
    final Constructor<?>[] cons = RandomStringUtils.class.getDeclaredConstructors();
    assertEquals(1, cons.length);/*w w w  . j a v  a2s .  c o  m*/
    assertTrue(Modifier.isPublic(cons[0].getModifiers()));
    assertTrue(Modifier.isPublic(RandomStringUtils.class.getModifiers()));
    assertFalse(Modifier.isFinal(RandomStringUtils.class.getModifiers()));
}

From source file:com.lexicalscope.fluentreflection.FluentFieldImpl.java

@Override
public boolean isFinal() {
    return Modifier.isFinal(field.getModifiers());
}

From source file:org.sonar.java.se.NullableAnnotationUtilsTest.java

@Test
public void private_constructor() throws Exception {
    assertThat(Modifier.isFinal(NullableAnnotationUtils.class.getModifiers())).isTrue();
    Constructor<NullableAnnotationUtils> constructor = NullableAnnotationUtils.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    assertThat(constructor.isAccessible()).isFalse();
    constructor.setAccessible(true);//from  w  w w  . j a  v  a  2  s  .c  o  m
    constructor.newInstance();
}