Example usage for java.lang.reflect Modifier isStatic

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

Introduction

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

Prototype

public static boolean isStatic(int mod) 

Source Link

Document

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

Usage

From source file:Debug.java

public static void setDebugLevel(Class cls, Debug level) throws NoSuchFieldException {
    try {/*ww  w  .  j  av a2s . c om*/
        Field fld = cls.getField("debug");
        if (fld.getType() != Debug.class || !Modifier.isStatic(fld.getModifiers()))
            throw new NoSuchFieldException();
        fld.set(null, level);
    } catch (IllegalArgumentException e) {
        throw new NoSuchFieldException();
    } catch (IllegalAccessException e) {
        throw new NoSuchFieldException();
    } catch (SecurityException e) {
        throw new NoSuchFieldException();
    }
}

From source file:utils.ReflectionService.java

public static Map createClassModel(Class clazz, int maxDeep) {
    Map map = new HashMap();
    for (Field field : clazz.getDeclaredFields()) {
        field.setAccessible(true);//from w  ww . j  a  v  a  2  s  . c  om
        String key = field.getName();
        try {
            Class<?> type;
            if (Collection.class.isAssignableFrom(field.getType())) {
                ParameterizedType collectionType = (ParameterizedType) field.getGenericType();
                type = (Class<?>) collectionType.getActualTypeArguments()[0];
            } else {
                type = field.getType();
            }

            //            System.out.println(key + " ReflectionResource.createClassModel ==== putting type: " + field.getType().getName() + ", static: "
            //            + Modifier.isStatic(field.getModifiers()) + ", enum: " + type.isEnum() + ", java.*: " + type.getName().startsWith("java"));

            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            } else if (type.isEnum()) {
                map.put(key, Enum.class.getName());
            } else if (!type.getName().startsWith("java") && !key.startsWith("_") && maxDeep > 0) {
                map.put(key, createClassModel(type, maxDeep - 1));
            } else {
                map.put(key, type.getName());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return map;
}

From source file:ch.algotrader.util.FieldUtil.java

/**
 * Returns all non-static / non-transient Fields including Fields defined by superclasses of the defined {@code type}
 *//* w  ww. j a v  a2 s.c o m*/
public static List<Field> getAllFields(Class<?> type) {

    List<Field> fields = new ArrayList<>();

    while (true) {

        for (Field field : type.getDeclaredFields()) {
            if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isTransient(field.getModifiers())) {
                setAccessible(field);
                fields.add(field);
            }
        }

        type = type.getSuperclass();
        if (type == Object.class || type == null) {
            break;
        }
    }

    return fields;
}

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  2s  .  c o  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:Mopex.java

/**
 * Returns an array of the instance variablies of the the specified class.
 * An instance variable is defined to be a non-static field that is declared
 * by the class or inherited.// w ww . j  av a 2  s .com
 * 
 * @return java.lang.Field[]
 * @param cls
 *            java.lang.Class
 */
//start extract getInstanceVariables
public static Field[] getInstanceVariables(Class cls) {
    List accum = new LinkedList();
    while (cls != null) {
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isStatic(fields[i].getModifiers())) {
                accum.add(fields[i]);
            }
        }
        cls = cls.getSuperclass();
    }
    Field[] retvalue = new Field[accum.size()];
    return (Field[]) accum.toArray(retvalue);
}

From source file:com.abiquo.model.util.ModelTransformer.java

public static <T> void transform(final Class sourceClass, final Class<T> targetClass, final Object source,
        final T target) throws Exception {
    Field[] transportFields = sourceClass.getDeclaredFields();
    Class superClass = sourceClass.getSuperclass();
    while (!superClass.getSimpleName().equalsIgnoreCase("SingleResourceTransportDto")) {
        transportFields = (Field[]) ArrayUtils.addAll(transportFields, superClass.getDeclaredFields());
        superClass = superClass.getSuperclass();
    }/* w w w . j ava2  s.c  om*/

    for (Field field : transportFields) {

        int modifiers = field.getModifiers();
        if (!Modifier.isTransient(modifiers) && !Modifier.isStatic(modifiers)) {
            String name = field.getName();
            try {
                if (fieldExist(name, targetClass) && fieldExist(name, source.getClass())
                        || getterExist(name, source.getClass())
                                && setterExist(name, targetClass, field.getType())) {
                    Object value = getter(name, source.getClass()).invoke(source, new Object[0]);

                    if (setterExist(name, targetClass, field.getType())) {
                        setter(name, targetClass, field.getType()).invoke(target, new Object[] { value });
                    }
                }
            } catch (InvocationTargetException e) {
                // Ignore invalid field
            }
        }

    }

}

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  .  ja v a 2s . 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:com.laxser.blitz.web.impl.module.ErrorHandlerDispatcher.java

public ErrorHandlerDispatcher(ControllerErrorHandler errorHandler) {
    this.errorHandler = errorHandler;
    Method[] methods = this.errorHandler.getClass().getMethods();
    for (final Method method : methods) {
        if (Modifier.isAbstract(method.getModifiers()) || Modifier.isStatic(method.getModifiers())) {
            continue;
        }// ww w .j a v  a 2 s  . c  o m
        if (method.getName().equals("onError")) {
            final Class<?>[] parameterClasses = method.getParameterTypes();
            if (parameterClasses.length == 2 && parameterClasses[INVOCATION_INDEX] == Invocation.class
                    && Throwable.class.isAssignableFrom(parameterClasses[THROWABLE_INDEX])) {
                delegates.add(new ErrorHandlerDelegate() {

                    @Override
                    public Method getMethod() {
                        return method;
                    }

                    @Override
                    public Object onError(Invocation inv, Throwable ex) throws Throwable {
                        Object[] args = new Object[] { inv, ex };
                        try {
                            return method.invoke(ErrorHandlerDispatcher.this.errorHandler, args);
                        } catch (Throwable e) {
                            logger.error("error happened when handling error " + ex.getClass() + " at "
                                    + ErrorHandlerDispatcher.this.toString());
                            throw e;
                        }
                    }
                });
            }
        }
    }
    Collections.sort(delegates, new Comparator<ErrorHandlerDelegate>() {

        @Override
        public int compare(ErrorHandlerDelegate o1, ErrorHandlerDelegate o2) {
            if (o1.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o2.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return 1;
            } else if (o2.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o1.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return -1;
            } else {
                return o1.getMethod().getParameterTypes()[THROWABLE_INDEX].getName()
                        .compareTo(o2.getMethod().getParameterTypes()[THROWABLE_INDEX].getName());
            }
        }
    });
}

From source file:com.sinosoft.one.mvc.web.impl.module.ErrorHandlerDispatcher.java

public ErrorHandlerDispatcher(ControllerErrorHandler errorHandler) {
    this.errorHandler = errorHandler;
    Method[] methods = this.errorHandler.getClass().getMethods();
    for (final Method method : methods) {
        if (Modifier.isAbstract(method.getModifiers()) || Modifier.isStatic(method.getModifiers())) {
            continue;
        }/*from   w ww .  jav a  2s  . c  o  m*/
        if (method.getName().equals("onError")) {
            final Class<?>[] parameterClasses = method.getParameterTypes();
            if (parameterClasses.length == 2 && parameterClasses[INVOCATION_INDEX] == Invocation.class
                    && Throwable.class.isAssignableFrom(parameterClasses[THROWABLE_INDEX])) {
                delegates.add(new ErrorHandlerDelegate() {

                    @Override
                    public Method getMethod() {
                        return method;
                    }

                    @Override
                    public Object onError(Invocation inv, Throwable ex) throws Throwable {
                        Object[] args = new Object[] { inv, ex };
                        try {
                            return method.invoke(ErrorHandlerDispatcher.this.errorHandler, args);
                        } catch (Throwable e) {
                            logger.error("error happened when handling error " + ex.getClass() + " at "
                                    + ErrorHandlerDispatcher.this.toString());
                            throw e;
                        }
                    }
                });
            }
        }
    }
    Collections.sort(delegates, new Comparator<ErrorHandlerDelegate>() {

        public int compare(ErrorHandlerDelegate o1, ErrorHandlerDelegate o2) {
            if (o1.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o2.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return 1;
            } else if (o2.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o1.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return -1;
            } else {
                return o1.getMethod().getParameterTypes()[THROWABLE_INDEX].getName()
                        .compareTo(o2.getMethod().getParameterTypes()[THROWABLE_INDEX].getName());
            }
        }
    });
}

From source file:de.cosmocode.palava.salesforce.sync.NullFieldCollector.java

private static void collect(Set<String> nullFields, Object object) {
    LOG.trace("Collecting null fields on {}", object);
    final Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (Modifier.isStatic(field.getModifiers()))
            continue;
        if ("fieldsToNull".equals(field.getName()))
            continue;
        try {/*  w w w. j a  v a 2 s .  c o m*/
            final boolean accessible = field.isAccessible();
            field.setAccessible(true);
            final Object value = field.get(object);
            field.setAccessible(accessible);
            if (value == null) {
                continue;
            } else if (value instanceof JAXBElement<?>) {
                final JAXBElement<?> jaxb = JAXBElement.class.cast(value);
                if (jaxb.getValue() == null) {
                    nullFields.add(nameOf(field));
                }
            }
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException(e);
        }
    }
    LOG.trace("Null fields on {}: {}", object, nullFields);
}