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:adalid.core.XS1.java

static boolean checkFieldAnnotation(boolean log, Field field, Class<? extends Annotation> annotation,
        Class<?>[] validTypes) {
    String name = field.getName();
    Class<?> type = field.getDeclaringClass();
    String string;//from  www .j a  v  a2s  .  c  o m
    int modifiers = field.getModifiers();
    if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
        string = "field " + name + " has static and/or final modifier";
        if (log) {
            logFieldAnnotationErrorMessage(name, type, annotation, string);
        }
        return false;
    }
    int length = validTypes == null ? 0 : validTypes.length;
    if (length < 1) {
        return true;
    }
    Class<?> ft = getTrueType(field.getType());
    String[] strings = new String[length];
    int i = 0;
    for (Class<?> vt : validTypes) {
        if (vt.isAssignableFrom(ft)) {
            return true;
        }
        strings[i++] = vt.getSimpleName();
    }
    string = "type of " + name + " is not " + StringUtils.join(strings, " or ");
    if (log) {
        logFieldAnnotationErrorMessage(name, type, annotation, string);
    }
    return false;
}

From source file:com.glaf.core.util.ReflectUtils.java

public static boolean isPublicInstanceField(Field field) {
    return Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())
            && !Modifier.isFinal(field.getModifiers()) && !field.isSynthetic();
}

From source file:org.latticesoft.util.common.StringUtil.java

public static String formatObjectToString(Object o, boolean includeChild) {
    if (o == null)
        return "";
    if (o == null)
        return "";

    StringBuffer sb = new StringBuffer();
    String className = o.getClass().getName();

    sb.append("[");
    sb.append(className);//from  w  ww  . j av  a 2s  .  c o  m
    sb.append("|");

    // list of attributes
    Field f[] = o.getClass().getDeclaredFields();
    WrapDynaBean dyn = null;
    try {
        dyn = new WrapDynaBean(o);
    } catch (Exception e) {
    }

    for (int i = 0; i < f.length; i++) {
        String name = f[i].getName();
        int modifier = f[i].getModifiers();
        if (Modifier.isFinal(modifier) || Modifier.isAbstract(modifier) || Modifier.isInterface(modifier)
                || Modifier.isStatic(modifier)) {
            continue;
        }
        Object value = null;
        try {
            value = dyn.get(name);
        } catch (Exception e) {
            //if (log.isErrorEnabled()) { log.error(e); }
        }
        if (name != null && value != null) {
            sb.append(name);
            sb.append("=");
            if (value instanceof Map) {
                Map map = (Map) value;
                if (includeChild) {
                    sb.append(value);
                } else {
                    sb.append(map.size());
                }
                sb.append("|");
            } else if (value instanceof Collection) {
                Collection c = (Collection) value;
                if (includeChild) {
                    sb.append(value);
                } else {
                    sb.append(c.size());
                }
                sb.append("|");
            } else {
                sb.append(value);
                sb.append("|");
            }
        }
    }
    sb.deleteCharAt(sb.length() - 1);
    sb.append("]");
    return sb.toString();
}

From source file:com.github.dozermapper.core.MappingProcessor.java

private Object mapArrayToArray(Object srcObj, Object srcCollectionValue, FieldMap fieldMap, Object destObj) {
    Class destEntryType = fieldMap.getDestFieldType(destObj.getClass()).getComponentType();
    Class srcEntryType = srcCollectionValue.getClass().getComponentType();
    int size = Array.getLength(srcCollectionValue);

    CopyByReferenceContainer copyByReferences = globalConfiguration.getCopyByReferences();
    boolean isPrimitiveArray = CollectionUtils.isPrimitiveArray(srcCollectionValue.getClass());
    boolean isFinal = Modifier.isFinal(srcEntryType.getModifiers());
    boolean isCopyByReference = copyByReferences.contains(srcEntryType);

    if (destEntryType.isAssignableFrom(srcEntryType) && isFinal && (isPrimitiveArray || isCopyByReference)) {
        return addArrayContentCopy(fieldMap, size, srcCollectionValue, destObj, destEntryType);
    } else if (isPrimitiveArray) {
        return addToPrimitiveArray(srcObj, fieldMap, size, srcCollectionValue, destObj, destEntryType);
    } else {/*from w  w w  .java 2s.c  o m*/
        List<?> list = Arrays.asList((Object[]) srcCollectionValue);
        List<?> returnList;
        if (!destEntryType.getName().equals(BASE_CLASS)) {
            returnList = addOrUpdateToList(srcObj, fieldMap, list, destObj, destEntryType);
        } else {
            returnList = addOrUpdateToList(srcObj, fieldMap, list, destObj, null);
        }
        return CollectionUtils.convertListToArray(returnList, destEntryType);
    }
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Parse callback methods into the given array, and return that array,
 * creating one if null. Each index into the array is a collection of
 * callback adapters for that numeric event type.
 *
 * @param sups whether to scan superclasses
 * @param listener whether this is a listener or not
 *//*  w w w .j a va  2  s .  c  om*/
public static Collection<LifecycleCallbacks>[] parseCallbackMethods(Class<?> cls,
        Collection<LifecycleCallbacks>[] callbacks, boolean sups, boolean listener, MetaDataRepository repos) {

    if (cls == null)
        throw new IllegalArgumentException("cls cannot be null");

    // first sort / filter based on inheritance
    Set<Method> methods = new TreeSet<Method>(MethodComparator.getInstance());

    int mods;
    Class<?> sup = cls;
    MethodKey key;
    Set<MethodKey> seen = new HashSet<MethodKey>();
    do {
        for (Method m : (Method[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredMethodsAction(sup))) {
            mods = m.getModifiers();
            if (Modifier.isStatic(mods) || Modifier.isFinal(mods) || Object.class.equals(m.getDeclaringClass()))
                continue;

            key = new MethodKey(m);
            if (!seen.contains(key)) {
                methods.add(m);
                seen.add(key);
            }
        }
        sup = sup.getSuperclass();
    } while (sups && !Object.class.equals(sup));

    OpenJPAConfiguration conf = repos.getConfiguration();
    for (Method m : methods) {
        for (Annotation anno : (Annotation[]) AccessController
                .doPrivileged(J2DoPrivHelper.getDeclaredAnnotationsAction(m))) {
            MetaDataTag tag = _tags.get(anno.annotationType());
            if (tag == null)
                continue;
            int[] events = MetaDataParsers.getEventTypes(tag, conf);
            if (events == null)
                continue;

            if (callbacks == null)
                callbacks = (Collection<LifecycleCallbacks>[]) new Collection[LifecycleEvent.ALL_EVENTS.length];

            for (int i = 0; i < events.length; i++) {
                int e = events[i];
                if (callbacks[e] == null)
                    callbacks[e] = new ArrayList<LifecycleCallbacks>(3);
                MetaDataParsers.validateMethodsForSameCallback(cls, callbacks[e], m, tag, conf, repos.getLog());
                if (listener) {
                    callbacks[e].add(new BeanLifecycleCallbacks(cls, m, false));
                } else {
                    callbacks[e].add(new MethodLifecycleCallbacks(m, false));
                }
            }
        }
    }
    return callbacks;
}

From source file:com.openddal.test.BaseTestCase.java

/**
 * Verify the next method call on the object will throw an exception.
 *
 * @param <T> the class of the object
 * @param verifier the result verifier to call
 * @param obj the object to wrap/*from   w  w w.  j a va2s .c  om*/
 * @return a proxy for the object
 */
@SuppressWarnings("unchecked")
protected <T> T assertThrows(final ResultVerifier verifier, final T obj) {
    Class<?> c = obj.getClass();
    InvocationHandler ih = new InvocationHandler() {
        private Exception called = new Exception("No method called");

        @Override
        protected void finalize() {
            if (called != null) {
                called.printStackTrace(System.err);
            }
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
            try {
                called = null;
                Object ret = method.invoke(obj, args);
                verifier.verify(ret, null, method, args);
                return ret;
            } catch (InvocationTargetException e) {
                verifier.verify(null, e.getTargetException(), method, args);
                Class<?> retClass = method.getReturnType();
                if (!retClass.isPrimitive()) {
                    return null;
                }
                if (retClass == boolean.class) {
                    return false;
                } else if (retClass == byte.class) {
                    return (byte) 0;
                } else if (retClass == char.class) {
                    return (char) 0;
                } else if (retClass == short.class) {
                    return (short) 0;
                } else if (retClass == int.class) {
                    return 0;
                } else if (retClass == long.class) {
                    return 0L;
                } else if (retClass == float.class) {
                    return 0F;
                } else if (retClass == double.class) {
                    return 0D;
                }
                return null;
            }
        }
    };
    if (!ProxyCodeGenerator.isGenerated(c)) {
        Class<?>[] interfaces = c.getInterfaces();
        if (Modifier.isFinal(c.getModifiers()) || (interfaces.length > 0 && getClass() != c)) {
            // interface class proxies
            if (interfaces.length == 0) {
                throw new RuntimeException("Can not create a proxy for the class " + c.getSimpleName()
                        + " because it doesn't implement any interfaces and is final");
            }
            return (T) Proxy.newProxyInstance(c.getClassLoader(), interfaces, ih);
        }
    }
    try {
        Class<?> pc = ProxyCodeGenerator.getClassProxy(c);
        Constructor<?> cons = pc.getConstructor(InvocationHandler.class);
        return (T) cons.newInstance(ih);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.jgentleframework.utils.ReflectUtils.java

/**
 * Returns <b>true</b> if given {@link Field} is <b>public, static,
 * final</b>, otherwise returns <b>false</b>.
 * //from  w  w w.  ja v a2  s .  co  m
 * @param field
 *            given {@link Field} need to be tested
 * @return true, if checks if is public static final
 */
public static boolean isPublicStaticFinal(Field field) {

    int modifiers = field.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
}

From source file:org.jgentleframework.utils.ReflectUtils.java

/**
 * Returns <b>true</b> if given {@link Method} is <b>public, static,
 * final</b>, otherwise returns <b>false</b>.
 * /*from  w w  w  .  j  av a  2s.  c  o  m*/
 * @param method
 *            given {@link Method} need to be tested
 * @return true, if checks if is public static final
 */
public static boolean isPublicStaticFinal(Method method) {

    int modifiers = method.getModifiers();
    return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Write Enumeration Complex Type//w  ww.  j a v a  2  s .c o  m
 * (Only supports enumeration classes of string types)
 *
 * @param qName QName of type.
 * @param cls   class of type
 * @return
 * @throws NoSuchMethodException
 * @throws IllegalAccessException
 * @throws AxisFault
 */
public Element writeEnumType(QName qName, Class cls)
        throws NoSuchMethodException, IllegalAccessException, AxisFault {

    if (!isEnumClass(cls)) {
        return null;
    }

    // Get the base type of the enum class
    java.lang.reflect.Method m = cls.getMethod("getValue", null);
    Class base = m.getReturnType();

    // Create simpleType, restriction elements
    Element simpleType = docHolder.createElement("simpleType");

    simpleType.setAttribute("name", qName.getLocalPart());

    Element restriction = docHolder.createElement("restriction");

    simpleType.appendChild(restriction);

    String baseType = writeType(base, null);

    restriction.setAttribute("base", baseType);

    // Create an enumeration using the field values
    Field[] fields = cls.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        int mod = field.getModifiers();

        // Inspect each public static final field of the same type
        // as the base
        if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod)
                && (field.getType() == base)) {

            // Create an enumeration using the value specified
            Element enumeration = docHolder.createElement("enumeration");

            enumeration.setAttribute("value", field.get(null).toString());
            restriction.appendChild(enumeration);
        }
    }

    return simpleType;
}

From source file:bammerbom.ultimatecore.bukkit.resources.utils.JsonRepresentedObject.java

private Object createChatPacket(String json) throws IllegalArgumentException, IllegalAccessException,
        InstantiationException, InvocationTargetException, NoSuchMethodException {
    if (nmsChatSerializerGsonInstance == null) {
        // Find the field and its value, completely bypassing obfuscation
        for (Field declaredField : Reflection.getNMSClass("ChatSerializer").getDeclaredFields()) {
            if (Modifier.isFinal(declaredField.getModifiers())
                    && Modifier.isStatic(declaredField.getModifiers())
                    && declaredField.getType().getName().endsWith("Gson")) {
                // We've found our field
                declaredField.setAccessible(true);
                nmsChatSerializerGsonInstance = declaredField.get(null);
                fromJsonMethod = nmsChatSerializerGsonInstance.getClass().getMethod("fromJson", String.class,
                        Class.class);
                break;
            }//from  w  w w . ja  va2  s  .  c  o m
        }
    }

    // Since the method is so simple, and all the obfuscated methods have the same name, it's easier to reimplement 'IChatBaseComponent a(String)' than to reflectively call it
    // Of course, the implementation may change, but fuzzy matches might break with signature changes
    Object serializedChatComponent = fromJsonMethod.invoke(nmsChatSerializerGsonInstance, json,
            Reflection.getNMSClass("IChatBaseComponent"));

    return nmsPacketPlayOutChatConstructor.newInstance(serializedChatComponent);
}