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:com.github.jknack.handlebars.internal.BaseTemplate.java

/**
 * Creates a new {@link TypeSafeTemplate}.
 *
 * @param rootType The target type./*from  ww w  . j a v a2 s . c  o  m*/
 * @param template The target template.
 * @return A new {@link TypeSafeTemplate}.
 */
private static Object newTypeSafeTemplate(final Class<?> rootType, final Template template) {
    return Proxy.newProxyInstance(template.getClass().getClassLoader(), new Class[] { rootType },
            new InvocationHandler() {
                private Map<String, Object> attributes = new HashMap<String, Object>();

                @Override
                public Object invoke(final Object proxy, final Method method, final Object[] args)
                        throws IOException {
                    String methodName = method.getName();
                    if ("apply".equals(methodName)) {
                        Context context = Context.newBuilder(args[0]).combine(attributes).build();
                        attributes.clear();
                        if (args.length == 2) {
                            template.apply(context, (Writer) args[1]);
                            return null;
                        }
                        return template.apply(context);
                    }

                    if (Modifier.isPublic(method.getModifiers()) && methodName.startsWith("set")) {
                        String attrName = StringUtils.uncapitalize(methodName.substring("set".length()));
                        if (args != null && args.length == 1 && attrName.length() > 0) {
                            attributes.put(attrName, args[0]);
                            if (TypeSafeTemplate.class.isAssignableFrom(method.getReturnType())) {
                                return proxy;
                            }
                            return null;
                        }
                    }
                    String message = String.format(
                            "No handler method for: '%s(%s)', expected method signature is: 'setXxx(value)'",
                            methodName, args == null ? "" : join(args, ", "));
                    throw new UnsupportedOperationException(message);
                }
            });
}

From source file:cn.aposoft.util.spring.ReflectionUtils.java

private static List<Method> findConcreteMethodsOnInterfaces(Class<?> clazz) {
    List<Method> result = null;
    for (Class<?> ifc : clazz.getInterfaces()) {
        for (Method ifcMethod : ifc.getMethods()) {
            if (!Modifier.isAbstract(ifcMethod.getModifiers())) {
                if (result == null) {
                    result = new LinkedList<Method>();
                }/*from  w  w w  . ja  v  a2 s.  c o m*/
                result.add(ifcMethod);
            }
        }
    }
    return result;
}

From source file:com.jeeframework.util.classes.ClassUtils.java

/**
 * Return a static method of a class./*from w ww  .j  ava2s  .c o  m*/
 * @param methodName the static method name
 * @param clazz   the class which defines the method
 * @param args the parameter types to the method
 * @return the static method, or <code>null</code> if no static method was found
 * @throws IllegalArgumentException if the method name is blank or the clazz is null
 */
public static Method getStaticMethod(Class clazz, String methodName, Class[] args) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    try {
        Method method = clazz.getDeclaredMethod(methodName, args);
        if ((method.getModifiers() & Modifier.STATIC) != 0) {
            return method;
        }
    } catch (NoSuchMethodException ex) {
    }
    return null;
}

From source file:grails.util.GrailsClassUtils.java

/**
 * Check whether the specified method is a property getter
 *
 * @param method The method//  w w w  . ja v  a  2 s . c o m
 * @return true if the method is a property getter
 */
public static boolean isPropertyGetter(Method method) {
    return !Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())
            && GrailsNameUtils.isGetter(method.getName(), method.getReturnType(), method.getParameterTypes());
}

From source file:io.stallion.reflection.PropertyUtils.java

public static <T extends Annotation> T getAnnotationForProperty(Class cls, String name, Class<T> anno) {
    String postFix = name.toUpperCase();
    if (name.length() > 1) {
        postFix = name.substring(0, 1).toUpperCase() + name.substring(1);
    }//  w  w w.j a  va 2s  .  co m
    Method method = null;
    try {
        method = cls.getMethod("get" + postFix);
    } catch (NoSuchMethodException e) {

    }
    if (method == null) {
        try {
            method = cls.getMethod("is" + postFix);
        } catch (NoSuchMethodException e) {

        }
    }
    if (method == null) {
        return null;
    }
    if (method.getModifiers() != Modifier.PUBLIC) {
        return null;
    }
    if (method.isAnnotationPresent(anno)) {
        return method.getDeclaredAnnotation(anno);
    }
    return null;
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.FactoryDescriptionHelper.java

/**
 * Implementation of {@link #getDescriptionsMap0(AstEditor, Class, boolean)} that can throw
 * exceptions.//from  ww w .  ja v a2 s . com
 */
private static Map<String, FactoryMethodDescription> getDescriptionsMap0Ex(AstEditor editor,
        Class<?> factoryClass, boolean forStatic) throws Exception {
    EditorState state = EditorState.get(editor);
    ILoadingContext context = EditorStateLoadingContext.get(state);
    // try to find cached map
    {
        Map<String, FactoryMethodDescription> signaturesMap = state.getFactorySignatures(factoryClass,
                forStatic);
        if (signaturesMap != null) {
            return signaturesMap;
        }
    }
    //
    String factoryClassName = factoryClass.getName();
    IType factoryType = editor.getJavaProject().findType(factoryClassName);
    if (factoryType == null) {
        return Maps.newTreeMap();
    }
    Boolean allMethodsAreFactories = null;
    List<FactoryMethodDescription> descriptions = Lists.newArrayList();
    // read descriptions from XML
    {
        String descriptionName = factoryClassName.replace('.', '/') + ".wbp-factory.xml";
        ResourceInfo resourceInfo = DescriptionHelper.getResourceInfo(context, factoryClass, descriptionName);
        if (resourceInfo != null) {
            Map<Integer, FactoryMethodDescription> textualDescriptions = Maps.newHashMap();
            Digester digester = prepareDigester(factoryClass, state, textualDescriptions);
            digester.push(allMethodsAreFactories);
            digester.push(descriptions);
            allMethodsAreFactories = (Boolean) digester.parse(resourceInfo.getURL());
            readTextualDescriptions(resourceInfo, textualDescriptions);
        }
    }
    // prepare map: signature -> description
    Map<String, FactoryMethodDescription> signaturesMap = Maps.newTreeMap();
    for (FactoryMethodDescription description : descriptions) {
        signaturesMap.put(description.getSignature(), description);
    }
    // factory flag for not-wbp methods
    if (allMethodsAreFactories == null) {
        allMethodsAreFactories = hasFactorySuffix(factoryType) || hasFactoryTag(factoryType);
    }
    // if no methods from XML, may be no methods at all
    if (!allMethodsAreFactories.booleanValue() && descriptions.isEmpty() && !hasFactoryTagSource(factoryType)) {
        return Maps.newTreeMap();
    }
    // add descriptions for all methods, using JavaDoc
    {
        // prepare methods
        Method[] methods;
        IMethod[] modelMethods;
        {
            methods = factoryClass.getDeclaredMethods();
            // prepare signatures for "public static" methods
            String[] signatures = new String[methods.length];
            for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
                Method factoryMethod = methods[methodIndex];
                // check modifiers
                {
                    int modifiers = factoryMethod.getModifiers();
                    if (!hasValidVisibility(editor, factoryMethod)) {
                        continue;
                    }
                    if (forStatic && !java.lang.reflect.Modifier.isStatic(modifiers)) {
                        continue;
                    }
                }
                // check return type
                {
                    Class<?> returnType = factoryMethod.getReturnType();
                    // method that returns "primitive" can not be factory method
                    if (returnType.isPrimitive()) {
                        continue;
                    }
                    // special case - filter out getters
                    if (factoryMethod.getParameterTypes().length == 0
                            && factoryMethod.getName().startsWith("get")) {
                        continue;
                    }
                }
                // OK, valid method
                signatures[methodIndex] = ReflectionUtils.getMethodSignature(factoryMethod);
            }
            // prepare model methods
            modelMethods = CodeUtils.findMethods(factoryType, signatures);
        }
        // prepare factory description for each method
        for (int methodIndex = 0; methodIndex < methods.length; methodIndex++) {
            Method factoryMethod = methods[methodIndex];
            IMethod modelMethod = modelMethods[methodIndex];
            if (modelMethod == null) {
                continue;
            }
            // prepare description
            FactoryMethodDescription description;
            {
                String signature = ReflectionUtils.getMethodSignature(factoryMethod);
                description = signaturesMap.get(signature);
                // create description if not exists
                if (description == null) {
                    description = new FactoryMethodDescription(factoryClass);
                    description.setName(factoryMethod.getName());
                    description.setFactory(allMethodsAreFactories);
                    signaturesMap.put(signature, description);
                }
            }
            // configure description
            description.setModelMethod(modelMethod);
            description.setReturnClass(factoryMethod.getReturnType());
            // check parameters
            {
                Class<?>[] parameterTypes = factoryMethod.getParameterTypes();
                for (int parameterIndex = 0; parameterIndex < parameterTypes.length; parameterIndex++) {
                    Class<?> parameterType = parameterTypes[parameterIndex];
                    // prepare parameter
                    ParameterDescription parameterDescription;
                    if (parameterIndex < description.getParameters().size()) {
                        parameterDescription = description.getParameter(parameterIndex);
                    } else {
                        parameterDescription = new ParameterDescription();
                        parameterDescription.setType(parameterType);
                        description.addParameter(parameterDescription);
                    }
                }
                //
                description.postProcess();
            }
            // try to mark as factory
            if (!description.isFactory()) {
                updateDescriptionsJavaDoc0(editor, description);
            }
        }
    }
    // remove incompatible instance/static methods
    for (Iterator<FactoryMethodDescription> I = signaturesMap.values().iterator(); I.hasNext();) {
        FactoryMethodDescription description = I.next();
        Method method = ReflectionUtils.getMethodBySignature(factoryClass, description.getSignature());
        int modifiers = method.getModifiers();
        if (forStatic ^ java.lang.reflect.Modifier.isStatic(modifiers)) {
            I.remove();
        }
    }
    // remove descriptions without "factory" flag
    for (Iterator<FactoryMethodDescription> I = signaturesMap.values().iterator(); I.hasNext();) {
        FactoryMethodDescription description = I.next();
        if (!description.isFactory()) {
            I.remove();
        }
    }
    // process JavaDoc
    for (FactoryMethodDescription description : signaturesMap.values()) {
        updateDescriptionsJavaDoc(editor, description);
    }
    // load icons
    for (Map.Entry<String, FactoryMethodDescription> entry : signaturesMap.entrySet()) {
        FactoryMethodDescription description = entry.getValue();
        // prepare icon
        Image icon;
        {
            String signature = entry.getKey();
            String signatureUnix = StringUtils.replaceChars(signature, "(,)", "___");
            String iconPath = factoryClassName.replace('.', '/') + "." + signatureUnix;
            icon = DescriptionHelper.getIconImage(context, iconPath);
            description.setIcon(icon);
        }
        // schedule disposing
        {
            String name = description.getDeclaringClass().getName() + "." + description.getSignature();
            ImageDisposer.add(description, name, icon);
        }
    }
    // remember descriptions in cache
    state.putFactorySignatures(factoryClass, forStatic, signaturesMap);
    return signaturesMap;
}

From source file:org.apache.openjpa.enhance.Reflection.java

/**
 * Return the return value of the given getter in the given object.
 *//*from   www  .  j  a  v  a 2s .c  om*/
public static Object get(Object target, Method getter) {
    if (target == null || getter == null)
        return null;
    makeAccessible(getter, getter.getModifiers());
    try {
        return getter.invoke(target, (Object[]) null);
    } catch (Throwable t) {
        throw wrapReflectionException(t, _loc.get("get-method", target, getter));
    }
}

From source file:org.echocat.adam.profile.ExtendedPeopleDirectoryAction.java

@Nonnull
protected static Method getMethod(@Nonnull Class<?> returnType, @Nonnull String methodName,
        @Nullable Class<?>... argumentTypes) {
    final Class<PeopleDirectoryAction> c = PeopleDirectoryAction.class;
    final Method method;
    try {/*from   ww  w . j  a v a 2 s  .  com*/
        method = c.getDeclaredMethod(methodName, argumentTypes);
    } catch (final NoSuchMethodException e) {
        throw new IllegalArgumentException("Could not find a method " + returnType.getName() + " " + c.getName()
                + "." + methodName + "(" + join(argumentTypes, ", ") + ").", e);
    }
    if (!method.getReturnType().equals(returnType)) {
        throw new IllegalArgumentException("Could not find a method " + returnType.getName() + " " + c.getName()
                + "." + methodName + "(" + join(argumentTypes, ", ") + ").");
    }
    if (isStatic(method.getModifiers())) {
        throw new IllegalArgumentException("Could not find a NOT STATIC method " + returnType.getName() + " "
                + c.getName() + "." + methodName + "(" + join(argumentTypes, ", ") + ").");
    }
    method.setAccessible(true);
    return method;
}

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

/**
 * Returns the specified default <code>getter</code> of the specified field.
 * /*  ww w . j  a  v a2s  .c  o  m*/
 * @param declaringClass
 *            the object class declared specified field.
 * @param fieldName
 *            name of field
 * @return returns the <code>getter</code> method if it exists, if not,
 *         return <code>null</code>.
 */
public static Method getDefaultGetter(Class<?> declaringClass, String fieldName) {

    Method getter = null;
    fieldName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
    try {
        getter = ReflectUtils.getSupportedMethod(declaringClass, "get" + fieldName, null);
    } catch (NoSuchMethodException e) {
        try {
            getter = ReflectUtils.getSupportedMethod(declaringClass, "is" + fieldName, null);
        } catch (NoSuchMethodException e1) {
            return null;
        }
    }
    if (getter != null && !Modifier.isPublic(getter.getModifiers()))
        try {
            throw new IllegalAccessException();
        } catch (IllegalAccessException e) {
            if (log.isErrorEnabled()) {
                log.error("The getter method [" + getter.getName() + "] declared in [" + declaringClass
                        + "] must be public", e);
            }
        }
    return getter;
}

From source file:com.duy.pascal.interperter.libraries.PascalLibraryManager.java

public static ArrayList<DescriptionImpl> getAllMethodDescription(Class<?>... classes) {
    ArrayList<DescriptionImpl> suggestItems = new ArrayList<>();
    for (Class<?> aClass : classes) {
        Method[] methods = aClass.getDeclaredMethods();
        for (Method method : methods) {
            if (AndroidLibraryUtils.getSdkVersion() >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                if (method.getAnnotation(PascalMethod.class) != null) {
                    PascalMethod annotation = method.getAnnotation(PascalMethod.class);
                    String description = annotation.description();
                    // TODO: 17-Aug-17
                    //                        suggestItems.add(new FunctionDescription(StructureType.TYPE_FUNCTION,
                    //                                Name.create(method.getName()), description, method.));
                }//from w  w  w. j  ava  2s.  co  m
            } else {
                if (Modifier.isPublic(method.getModifiers())) {
                    suggestItems.add(new DescriptionImpl(StructureType.TYPE_FUNCTION, method.getName()));
                }
            }
        }
    }
    return suggestItems;
}