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:it.unibas.spicy.persistence.object.operators.AnalyzeFields.java

private boolean findPublicMethodInClass(Class currentClass, String methodName) {
    Method[] methods = currentClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName) && Modifier.isPublic(method.getModifiers())) {
            return true;
        }/*www  .  jav  a 2  s  .  co m*/
    }
    return false;
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

/**
 * this method generate record instance by calling newIntance
 * using reflection, add register the generated value to typeValueCache
 *//*from  ww w. j  a va 2 s.  c  o  m*/
@SuppressWarnings("rawtypes")
private static Object generateByNewInstance(Class clazz) throws Exception {
    Object ret = typeValueCache.get(clazz);
    if (ret != null) {
        return ret;
    }
    Method newInstance = null;
    Type[] paramTypes = new Type[0];
    // get newInstance method with most parameters
    for (Method m : clazz.getMethods()) {
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(clazz) && Modifier.isPublic(mod) && Modifier.isStatic(mod)
                && m.getName().equals("newInstance")) {
            Type[] pts = m.getGenericParameterTypes();
            if (newInstance == null || (pts.length > paramTypes.length)) {
                newInstance = m;
                paramTypes = pts;
            }
        }
    }
    if (newInstance == null) {
        throw new IllegalArgumentException("type " + clazz.getName() + " does not have newInstance method");
    }
    Object[] args = new Object[paramTypes.length];
    for (int i = 0; i < args.length; i++) {
        args[i] = genTypeValue(paramTypes[i]);
    }
    ret = newInstance.invoke(null, args);
    typeValueCache.put(clazz, ret);
    return ret;
}

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

/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).//from ww w .  ja v  a  2s  .c  o m
 * 
 * @param method
 *            the method to make accessible
 * @see java.lang.reflect.Method#setAccessible(boolean)
 */
public static void makeAccessible(Method method) {

    if (!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
        method.setAccessible(true);
    }
}

From source file:com.github.jknack.handlebars.helper.DefaultHelperRegistry.java

/**
 * <p>//ww  w.  j av a2 s . c  o  m
 * Register all the helper methods for the given helper source.
 * </p>
 *
 * @param source The helper source.
 * @param clazz The helper source class.
 */
private void registerDynamicHelper(final Object source, final Class<?> clazz) {
    int size = helpers.size();
    int replaced = 0;
    if (clazz != Object.class) {
        Set<String> overloaded = new HashSet<String>();
        // Keep backing up the inheritance hierarchy.
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            boolean isPublic = Modifier.isPublic(method.getModifiers());
            String helperName = method.getName();
            if (isPublic && CharSequence.class.isAssignableFrom(method.getReturnType())) {
                boolean isStatic = Modifier.isStatic(method.getModifiers());
                if (source != null || isStatic) {
                    if (helpers.containsKey(helperName)) {
                        replaced++;
                    }
                    isTrue(overloaded.add(helperName), "name conflict found: " + helperName);
                    registerHelper(helperName, new MethodHelper(method, source));
                }
            }
        }
    }
    isTrue((size + replaced) != helpers.size(), "No helper method was found in: " + clazz.getName());
}

From source file:java2typescript.jackson.module.visitors.TSJsonObjectFormatVisitor.java

void addPublicMethods() {

    for (Method method : this.clazz.getDeclaredMethods()) {

        // Only public
        if (!isPublic(method.getModifiers())) {
            continue;
        }//  w ww. j  a  va 2 s.c om

        // Exclude accessors
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            if (isAccessorMethod(method, beanInfo)) {
                continue;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        if (conf.isIgnoredMethod(method)) {
            continue;
        }

        addMethod(method);
    }
}

From source file:org.jgentleframework.core.factory.support.CommonFactory.java

/**
 * Do init./*from   w  ww. j  a v a2s  . c o m*/
 * 
 * @param definition
 *            the definition
 * @param obj
 *            object bean
 * @param clazz
 *            the <code>object class</code>
 * @throws InvocationTargetException
 *             the invocation target exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws IllegalArgumentException
 *             the illegal argument exception
 * @throws NoSuchMethodException
 *             the no such method exception
 * @throws SecurityException
 *             the security exception
 */
public void doInit(Definition definition, Object obj, Class<?> clazz) throws IllegalArgumentException,
        IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException {

    if (ReflectUtils.isCast(Initializing.class, obj)) {
        ((Initializing) obj).initialize();
    } else {
        List<Method> methods = definition.getMethodsAnnotatedWith(InitializingMethod.class);
        if (methods != null && methods.size() != 0) {
            for (Method method : methods) {
                if (Modifier.isPublic(method.getModifiers())) {
                    FastClass fclass = FastClass.create(method.getDeclaringClass());
                    FastMethod fmethod = fclass.getMethod(method);
                    fmethod.invoke(obj, null);
                } else {
                    if (log.isErrorEnabled()) {
                        log.error("The initializing method must be public !");
                    }
                }
            }
        }
    }
    // else {
    //         
    // ReflectUtils.invokeMethod(obj, "init", null, null, true, true);
    // }
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build JSP function models from an annotated class
 * @param type class with annotated static methods
 * @return JSP function models/*from  ww  w . j  a  va2 s . com*/
 */
public Collection<JspFunctionModel> getFunctionMetadata(Class<?> type) {
    Collection<JspFunctionModel> functions = new ArrayList<JspFunctionModel>();
    for (Method method : type.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())
                && method.isAnnotationPresent(JspFunction.class)) {
            JspFunction functionAnnotation = method.getAnnotation(JspFunction.class);
            JspFunctionModel metadata = new JspFunctionModel();
            metadata.name = functionAnnotation.name();
            metadata.functionClass = type.getName();
            JspFunctionSignature signature = new JspFunctionSignature();
            signature.name = method.getName();
            signature.argumentTypes = method.getParameterTypes();
            signature.returnType = method.getReturnType();
            metadata.signature = signature;
            functions.add(metadata);
        }
    }
    return functions;
}

From source file:net.sf.beanlib.provider.BeanChecker.java

/** 
 * Returns true if the fromBean is empty; or false otherwise.
 * It is considered empty if every publicly declared getter methods of the specified class 
 * either return null or blank string./*  w  w  w  . ja v  a  2  s  .  co m*/
 * 
 * @param fromBean java bean to check if empty or not.
 * @param k specified class name from which the getter methods are derived. 
 */
public boolean empty(Object fromBean, Class<?> k) {
    Class<?> fromClass = fromBean.getClass();
    Method[] ma = k.getDeclaredMethods();
    try {
        // invoking all declaring getter methods of fromBean
        for (int i = 0; i < ma.length; i++) {
            Method m = ma[i];
            String name = m.getName();
            try {
                if (name.startsWith("get") && Modifier.isPublic(m.getModifiers())) {
                    Method getter = fromClass.getMethod(name);
                    Object attrValue = getter.invoke(fromBean);

                    if (attrValue == null) {
                        continue;
                    }
                    if (attrValue instanceof String) {
                        String s = (String) attrValue;
                        s = s.trim();

                        if (s.length() == 0) {
                            continue;
                        }
                    }
                    return false;
                }
            } catch (NoSuchMethodException ignore) {
                // ignore and proceed to the next method.
            }
        }
        return true;
    } catch (IllegalAccessException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } catch (SecurityException e) {
        log.error("", e);
        throw new BeanlibException(e);
    } catch (InvocationTargetException e) {
        log.error("", e.getTargetException());
        throw new BeanlibException(e.getTargetException());
    }
}

From source file:com.strandls.alchemy.rest.client.RestInterfaceAnalyzer.java

/**
 * Analyze the class and build the meta information.
 *
 * @param klass//from  www  . j  ava2s .  c om
 *            the class.
 * @return analyzed metadata.
 * @throws NotRestInterfaceException
 *             if the class analyzed is not a rest interface.
 */
protected RestInterfaceMetadata doAnalyze(final Class<?> klass) throws NotRestInterfaceException {
    final List<String> produced = new ArrayList<String>();
    final List<String> consumed = new ArrayList<String>();
    String path = null;

    @SuppressWarnings("unchecked")
    final Set<Annotation> declaredAnnotationList = ReflectionUtils.getAllAnnotations(klass);
    for (final Annotation annotation : declaredAnnotationList) {
        if (annotation instanceof Path) {
            path = ((Path) annotation).value();
        } else if (annotation instanceof Produces) {
            final Produces produces = (Produces) annotation;
            final String[] values = produces.value();
            produced.addAll(Arrays.asList(values));
        } else if (annotation instanceof Consumes) {
            final Consumes consumes = (Consumes) annotation;
            final String[] values = consumes.value();
            consumed.addAll(Arrays.asList(values));
        }
    }

    final Map<Method, RestMethodMetadata> methodMetadataMap = new LinkedHashMap<Method, RestMethodMetadata>();

    @SuppressWarnings("unchecked")
    final Set<Method> methods = ReflectionUtils.getAllMethods(klass, new Predicate<Method>() {
        @Override
        public boolean apply(final Method input) {
            // return only public methods
            return Modifier.isPublic(input.getModifiers());
        }
    });

    for (final Method method : methods) {
        final RestMethodMetadata methodMetadata = analyzeMethod(method);
        if (methodMetadata != null) {
            methodMetadataMap.put(method, methodMetadata);
        }
    }

    if (methodMetadataMap.isEmpty()) {
        // not a valid rest interface.
        throw new NotRestInterfaceException(klass);
    }

    return new RestInterfaceMetadata(path, produced, consumed, methodMetadataMap);
}

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

public static void setFieldValue(Object target, String name, Class<?> type, Object value) {
    if (target == null || StringUtils.isEmpty(name)
            || (value != null && !type.isAssignableFrom(value.getClass()))) {
        return;/*from  ww w  .  ja  va2s.  c  o m*/
    }
    Class<?> clazz = target.getClass();
    try {
        Method method = clazz
                .getDeclaredMethod("set" + Character.toUpperCase(name.charAt(0)) + name.substring(1), type);
        if (!Modifier.isPublic(method.getModifiers())) {
            method.setAccessible(true);
        }
        method.invoke(target, value);
    } catch (Exception ex) {
        if (LogUtils.isDebug()) {
            logger.debug(ex);
        }
        try {
            Field field = clazz.getDeclaredField(name);
            if (!Modifier.isPublic(field.getModifiers())) {
                field.setAccessible(true);
            }
            field.set(target, value);
        } catch (Exception e) {
            if (LogUtils.isDebug()) {
                logger.debug(e);
            }
        }
    }
}