Example usage for java.lang.reflect Method getModifiers

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

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:org.istsms.util.Javabean2JSON.java

private static void addAttributes(Object obj, Class c, JSONObject jObj) {
    //String objectClass=c.getCanonicalName();
    //      Method[] m=c.getDeclaredMethods();
    Method[] m = c.getMethods();/*from  www .  j  a  v a2s.  com*/
    //Note: private and protected methods are not considered!
    Method method;
    String methodName;
    for (int i = 0; i < m.length; i++) {
        method = m[i];
        if (Modifier.isStatic(method.getModifiers()))
            continue;
        if (!method.getDeclaringClass().equals(c))
            continue; //it is an inherited method, do not consider
        //TODO:maybe also private and protected methods have to be discarder!
        methodName = method.getName();
        if (methodName.startsWith("get") || methodName.startsWith("is")) {
            Class[] params = method.getParameterTypes();
            if (params.length == 0) {
                String key;
                if (methodName.startsWith("get"))
                    key = methodName.substring(3);
                else
                    key = methodName.substring(2);
                String type = method.getReturnType().getCanonicalName();
                log("found method GET " + key + " returned type: " + type);
                Object value;
                try {
                    value = method.invoke(obj, (Object[]) null);
                    //now enumerate primitive types, if it is a primitive value, put it in the json object
                    //its value as a string; otherwise call recursively this method
                    if (value == null)
                        continue;
                    if (value.getClass().isArray()) {
                        //it's an array!      
                        JSONArray ja = _toJSONArray(value, method.getReturnType()); //10.07.08 GB to support array of array serialization
                        if (ja != null)
                            jObj.put(key, ja);
                    } else {
                        put(jObj, type, key, value);
                    }

                } catch (Exception e) {
                    log("Exception: " + e.getMessage());
                }
            }
        }
    }
}

From source file:org.batoo.jpa.common.reflect.ReflectHelper.java

/**
 * Returns the property descriptors for the class.
 * /* ww w.  j  a v  a2 s . co m*/
 * @param clazz
 *            the class
 * @return the property descriptors
 * 
 * @since $version
 * @author hceylan
 */
public static PropertyDescriptor[] getProperties(Class<?> clazz) {
    final List<PropertyDescriptor> properties = Lists.newArrayList();

    final Method[] methodList = clazz.getDeclaredMethods();

    // check each method.
    for (final Method method : methodList) {
        if (method == null) {
            continue;
        }

        // skip static and private methods.
        final int mods = method.getModifiers();
        if (Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
            continue;
        }

        final String name = method.getName();

        if (method.getParameterTypes().length == 0) {
            if (name.startsWith(ReflectHelper.GET_PREFIX)) {
                properties.add(new PropertyDescriptor(clazz, name.substring(3), method));
            } else if ((method.getReturnType() == boolean.class) && name.startsWith(ReflectHelper.IS_PREFIX)) {
                properties.add(new PropertyDescriptor(clazz, name.substring(2), method));
            }
        }
    }

    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:net.jodah.typetools.TypeResolver.java

/**
 * Populates the {@code map} with variable/argument pairs for the {@code functionalInterface}.
 */// www . j a  v a2s  .  co m
private static void populateLambdaArgs(Class<?> functionalInterface, final Class<?> lambdaType,
        Map<TypeVariable<?>, Type> map) {
    if (GET_CONSTANT_POOL != null) {
        try {
            // Find SAM
            for (Method m : functionalInterface.getMethods()) {
                if (!m.isDefault() && !Modifier.isStatic(m.getModifiers()) && !m.isBridge()) {
                    // Skip methods that override Object.class
                    Method objectMethod = OBJECT_METHODS.get(m.getName());
                    if (objectMethod != null
                            && Arrays.equals(m.getTypeParameters(), objectMethod.getTypeParameters()))
                        continue;

                    // Get functional interface's type params
                    Type returnTypeVar = m.getGenericReturnType();
                    Type[] paramTypeVars = m.getGenericParameterTypes();

                    // Get lambda's type arguments
                    ConstantPool constantPool = (ConstantPool) GET_CONSTANT_POOL.invoke(lambdaType);
                    String[] methodRefInfo = constantPool.getMemberRefInfoAt(
                            constantPool.getSize() - resolveMethodRefOffset(constantPool, lambdaType));

                    // Skip auto boxing methods
                    if (methodRefInfo[1].equals("valueOf") && constantPool.getSize() > 22) {
                        try {
                            methodRefInfo = constantPool.getMemberRefInfoAt(constantPool.getSize()
                                    - resolveAutoboxedMethodRefOffset(constantPool, lambdaType));
                        } catch (MethodRefOffsetResolutionFailed ignore) {
                        }
                    }

                    if (returnTypeVar instanceof TypeVariable) {
                        Class<?> returnType = TypeDescriptor.getReturnType(methodRefInfo[2])
                                .getType(lambdaType.getClassLoader());
                        if (!returnType.equals(Void.class))
                            map.put((TypeVariable<?>) returnTypeVar, returnType);
                    }

                    TypeDescriptor[] arguments = TypeDescriptor.getArgumentTypes(methodRefInfo[2]);

                    // Handle arbitrary object instance method references
                    int paramOffset = 0;
                    if (paramTypeVars[0] instanceof TypeVariable
                            && paramTypeVars.length == arguments.length + 1) {
                        Class<?> instanceType = TypeDescriptor.getObjectType(methodRefInfo[0])
                                .getType(lambdaType.getClassLoader());
                        map.put((TypeVariable<?>) paramTypeVars[0], instanceType);
                        paramOffset = 1;
                    }

                    // Handle local final variables from context that are passed as arguments.
                    int argOffset = 0;
                    if (paramTypeVars.length < arguments.length) {
                        argOffset = arguments.length - paramTypeVars.length;
                    }

                    for (int i = 0; i + argOffset < arguments.length; i++) {
                        if (paramTypeVars[i] instanceof TypeVariable) {
                            map.put((TypeVariable<?>) paramTypeVars[i + paramOffset],
                                    arguments[i + argOffset].getType(lambdaType.getClassLoader()));
                        }
                    }
                    break;
                }
            }

        } catch (Exception ignore) {
        }
    }
}

From source file:Mopex.java

/**
 * This method retrieves the modifiers of a Method without the unwanted
 * modifiers specified in the second parameter. Because this method uses
 * bitwise operations, multiple unwanted modifiers may be specified by
 * bitwise or./*from   w  ww  .ja  v a2s . c  o m*/
 * 
 * @return int
 * @param m
 *            java.lang.Method
 * @param unwantedModifiers
 *            int
 */
//start extract getModifiersWithout
public static int getModifiersWithout(Method m, int unwantedModifiers) {
    int mods = m.getModifiers();
    return (mods ^ unwantedModifiers) & mods;
}

From source file:Mopex.java

/**
 * Returns a String that represents the header of a method.
 * //from w  w w  . ja v  a2 s.  c om
 * @return String
 * @param m
 *            java.lang.Method
 */
//start extract headerToString
public static String headerToString(Method m) {
    String mods = Modifier.toString(m.getModifiers());
    if (mods.length() == 0)
        return headerSuffixToString(m);
    else
        return mods + " " + headerSuffixToString(m);
}

From source file:org.faster.opm.PropertyHelper.java

public static final boolean isPropertyMethod(Resource resource, Method method) {
    if (method.isAnnotationPresent(Property.class)) {
        return true;
    }/*  w  w w.  j a va  2  s.c o m*/
    if (resource.defaultPropertyStrategy() == PropertyStrategy.EXCLUDE) {
        return false;
    }
    if (Modifier.isStatic(method.getModifiers())) {
        return false;
    }
    return !method.isAnnotationPresent(ExcludeProperty.class);
}

From source file:org.istsms.util.Javabean2JSON.java

public static Object fromJSONObject(JSONObject jObj0, Class suggestion) {

    if ((suggestion != null) && (suggestion.equals(JSONObject.class)))
        return jObj0;
    JSONObject jObj = (JSONObject) jObj0;
    Class c;/* w ww  .j  av  a 2s .c o m*/
    String cl = null;
    if (suggestion != null)
        cl = suggestion.getCanonicalName();
    try {
        try {
            cl = jObj.getString("__class");
        } catch (JSONException e) {
        } catch (ClassCastException e) {
        }
        if (cl == null)
            return null;
        if (isPrimitive(cl)) {
            return getPrimitive(jObj0.getString("__value"), jObj0.getString("__class"));
        }
        if (isCalendar(cl)) {
            return toJavaCalendar(jObj0);
        }
        c = Class.forName(cl);
        Object temp = c.newInstance();
        Method[] m = c.getMethods();
        //Note: private and protected methods are not considered!
        Method method;
        String methodName;
        for (int i = 0; i < m.length; i++) {
            method = m[i];
            if (Modifier.isStatic(method.getModifiers()))
                continue;
            methodName = method.getName();
            if (methodName.startsWith("set")) {
                Class[] params = method.getParameterTypes();
                if (params.length == 1) {
                    //String key=methodName.substring(3); //ANDREA - cambiato in:
                    String key = methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                    String type = params[0].getCanonicalName();
                    if (params[0].isArray()) {
                        //it's an array!
                        //type=type.substring(0, type.length()-2); //skip '[]' now done inside _fromJSONArray()
                        JSONArray jArr = null;
                        try {
                            jArr = jObj.getJSONArray(key);
                        } catch (JSONException e) {
                        }
                        Object objArr = fromJSONArray(jArr, params[0]); //10.7.08 GB to support array of array deserialization
                        if (objArr != null)
                            method.invoke(temp, objArr);
                    } else {
                        Object value = null;
                        try {
                            value = jObj.get(key);
                        } catch (JSONException e) {
                        }
                        //if (value==null) continue; //ANDREA - cambiato in:
                        if (value == null || value.equals(null))
                            continue;
                        Object arg = null;
                        if (isCalendar(type))
                            try {
                                arg = toJavaCalendar((JSONObject) value);
                            } catch (ClassCastException e) {
                                e.printStackTrace();
                            }
                        else {
                            if (value instanceof JSONObject) {
                                arg = fromJSONObject((JSONObject) value, params[0]);
                            } else
                                arg = getPrimitive(value, type);
                        }
                        method.invoke(temp, new Object[] { arg });
                    }
                }
            }
        }
        return temp;
    } catch (Exception e) {
        e.printStackTrace();
        log(e.getMessage());
    }
    return null;
}

From source file:com.autobizlogic.abl.util.BeanUtil.java

/**
 * Get the method with the given name from the given class, provided that it takes one argument
 * of the provided type./*from  w ww  .j  a  v a2 s  .  co  m*/
 * @param cls The class who should have (or inherit) the method
 * @param methodName The name of the method
 * @param argClass If provided, the type of the sole argument to the method. If null, no argument is assumed.
 * @param onlyProtectedAndHigher If true, we will ignore private methods in the superclasses.
 * @return The method if found, otherwise null.
 */
private static Method getMethodFromClass(Class<?> cls, String methodName, Class<?> argClass,
        boolean onlyProtectedAndHigher) {

    Method[] allMethods = cls.getDeclaredMethods();
    for (Method meth : allMethods) {
        if (!meth.getName().equals(methodName))
            continue;

        if (onlyProtectedAndHigher) {
            int modifiers = meth.getModifiers();
            if (Modifier.isPrivate(modifiers))
                continue;
        }

        if (argClass != null) {
            Class<?>[] paramTypes = meth.getParameterTypes();
            if (paramTypes.length != 1)
                continue;

            Class<?> genericType = getGenericType(paramTypes[0]);
            if (!genericType.isAssignableFrom(argClass))
                continue;
        }

        // Note that if we're trying to set a value to null, we obviously cannot check the
        // signature for overloading, and therefore we'll return the first method which takes
        // one parameter. I think that's not that unreasonable, but it could conceivably break
        // if someone does funny things with their bean.

        return meth;
    }

    return null;
}

From source file:com.medallia.spider.api.StRenderer.java

/** @return the action method of the given class; throws AssertionError if no such method exists */
private static Method findActionMethod(Class<?> clazz) {
    Method am = ACTION_METHOD_MAP.get(clazz);
    if (am != null)
        return am;

    for (Method m : CollUtils.concat(Arrays.asList(clazz.getMethods()),
            Arrays.asList(clazz.getDeclaredMethods()))) {
        if (m.getName().equals("action")) {
            int modifiers = m.getModifiers();
            if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers))
                continue;
            m.setAccessible(true);/*from  w  w  w  .  java2  s.c o m*/
            ACTION_METHOD_MAP.put(clazz, m);
            return m;
        }
    }
    throw new AssertionError("No action method found in " + clazz);
}

From source file:com.yahoo.elide.core.EntityDictionary.java

/**
 * Find an arbitrary method.//from   w w  w  .  ja  v a  2 s  .  c o  m
 *
 * @param entityClass the entity class
 * @param name the name
 * @param paramClass the param class
 * @return method method
 * @throws NoSuchMethodException the no such method exception
 */
public static Method findMethod(Class<?> entityClass, String name, Class<?>... paramClass)
        throws NoSuchMethodException {
    Method m = entityClass.getMethod(name, paramClass);
    int modifiers = m.getModifiers();
    if (Modifier.isAbstract(modifiers)
            || (m.isAnnotationPresent(Transient.class) && !m.isAnnotationPresent(ComputedAttribute.class))) {
        throw new NoSuchMethodException(name);
    }
    return m;
}