Example usage for java.lang Class getDeclaredMethods

List of usage examples for java.lang Class getDeclaredMethods

Introduction

In this page you can find the example usage for java.lang Class getDeclaredMethods.

Prototype

@CallerSensitive
public Method[] getDeclaredMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the declared methods of the class or interface represented by this Class object, including public, protected, default (package) access, and private methods, but excluding inherited methods.

Usage

From source file:org.os890.ds.addon.remote.impl.server.ServiceConfigUpdateTask.java

private void createCacheEntryFor(Class<?> beanClass) {
    Path path = beanClass.getAnnotation(Path.class);

    if (path != null) {
        ObjectMapper objectMapper = new ObjectMapper();

        for (Method method : beanClass.getDeclaredMethods()) {
            Path methodPath = method.getAnnotation(Path.class);

            if (methodPath != null) {
                try {
                    ServiceDescriptor serviceDescriptor = ServiceDescriptorFactory.create(methodPath.value(),
                            path.value());
                    String serviceDescriptorAsJson = objectMapper.writeValueAsString(serviceDescriptor);
                    Cache<String, String> cache = cacheProvider.getCache();
                    String cachedValue = cache.get(serviceDescriptor.getKey());

                    if (!serviceDescriptorAsJson.equals(cachedValue)) {
                        cache.put(serviceDescriptor.getKey(), serviceDescriptorAsJson);
                    }/*from  w w  w.  j  a v a 2  s  .  c  o  m*/
                    LOG.fine("cached endpoint descriptor: " + serviceDescriptor.getKey() + " -> "
                            + serviceDescriptorAsJson);
                } catch (JsonProcessingException e) {
                    throw ExceptionUtils.throwAsRuntimeException(e);
                }
            }
        }
    }
}

From source file:org.apache.hadoop.metrics2.lib.MutableRatesWithAggregation.java

/**
 * Initialize the registry with all the methods in a protocol
 * so they all show up in the first snapshot.
 * Convenient for JMX implementations./*from   w w w  .  j  a  v a  2 s  .  c  o  m*/
 * @param protocol the protocol class
 */
public void init(Class<?> protocol) {
    if (protocolCache.contains(protocol)) {
        return;
    }
    protocolCache.add(protocol);
    for (Method method : protocol.getDeclaredMethods()) {
        String name = method.getName();
        LOG.debug(name);
        addMetricIfNotExists(name);
    }
}

From source file:ca.quadrilateral.btester.discovery.ParentInclusiveTestableMethodDiscoverer.java

private Set<MethodSetWrapper> getMethodWrappers(final Class<?> clazz) {
    final Set<MethodSetWrapper> wrapperSet = new HashSet<MethodSetWrapper>();

    if (clazz != null) {
        final Method[] declaredMethods = clazz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            final MethodSetWrapper methodWrapper = new MethodSetWrapper(method);
            if (!wrapperSet.contains(methodWrapper)) {
                wrapperSet.add(methodWrapper);
            }//from www  . ja v a2 s  . c o m
        }

        wrapperSet.addAll(getMethodWrappers(clazz.getSuperclass()));
    }

    return wrapperSet;
}

From source file:com.github.pith.typedconfig.TypedConfigPlugin.java

private Map<Class<Object>, Object> initConfigClasses(Collection<Class<?>> configClasses,
        Configuration configuration) {
    Map<Class<Object>, Object> configClassesMap = new HashMap<Class<Object>, Object>();

    for (Class<?> configClass : configClasses) {
        try {//ww  w . j  av a2s  . c o  m
            Object configObject = configClass.newInstance();
            for (Method method : configClass.getDeclaredMethods()) {
                if (method.getName().startsWith("get")) {
                    Object property = configuration.getProperty(configClass.getSimpleName().toLowerCase()
                            + method.getName().substring(3).toLowerCase());
                    if (property != null) {
                        try {
                            Method setter = configClass.getDeclaredMethod("set" + method.getName().substring(3),
                                    method.getReturnType());
                            setter.setAccessible(true);
                            setter.invoke(configObject, property);
                        } catch (NoSuchMethodException e) {
                            throw new IllegalStateException("The TypedConfigPlugin can't initialize "
                                    + method.getName() + " because there is no associated setter.");
                        } catch (InvocationTargetException e) {
                            if (e.getCause() != null) {
                                throw new IllegalStateException("Failed to initialize " + method.getName(),
                                        e.getCause());
                            }
                        }
                    }
                }
            }
            //noinspection unchecked
            configClassesMap.put((Class<Object>) configClass, configObject);
        } catch (InstantiationException e) {
            throw new IllegalStateException("Failed to instantiate " + configClass, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Failed to access the constructor of " + configClass, e.getCause());
        }
    }
    return configClassesMap;
}

From source file:ch.ifocusit.plantuml.classdiagram.ClassDiagramBuilder.java

public ClassMethod[] readMethods(Class aClass) {
    return Stream.of(aClass.getDeclaredMethods())
            // only public and non static methods
            .filter(method -> !Modifier.isStatic(method.getModifiers())
                    && Modifier.isPublic(method.getModifiers()))
            .map(this::createClassMethod)
            // excludes specific fields
            .filter(filterMethods()).sorted().toArray(ClassMethod[]::new);
}

From source file:de.micromata.genome.util.bean.PrivateBeanUtils.java

/**
 * Find method./*from  w  ww.j  ava 2s.c  om*/
 *
 * @param bean the bean
 * @param clazz the clazz
 * @param method the method
 * @param args the args
 * @return null if method cannot be found
 */
public static Method findMethod(Object bean, Class<?> clazz, String method, Object... args) {
    nextMethod: for (Method m : clazz.getDeclaredMethods()) {
        if (m.getName().equals(method) == false) {
            continue;
        }
        Class<?>[] argClazzes = m.getParameterTypes();
        if (argClazzes.length != args.length) {
            continue;
        }
        for (int i = 0; i < args.length; ++i) {
            Object a = args[i];
            Class<?> ac = argClazzes[i];
            if (a != null && ac.isAssignableFrom(a.getClass()) == false) {
                continue nextMethod;
            }
        }
        return m;
    }
    if (clazz != Object.class && clazz.getSuperclass() != null) {
        return findMethod(bean, clazz.getSuperclass(), method, args);
    }
    return null;
}

From source file:org.apache.ddlutils.util.CallbackClosure.java

/**
 * Creates a new closure object.//from w w w  .j ava 2  s. c  om
 * 
 * @param callee         The object on which the callbacks will be invoked
 * @param callbackName   The name of the callback method
 * @param parameterTypes The parameter types. This array has to contain one <code>null</code>
 *                       for the type of the object for which the callback is invoked.
 *                       <code>null</code> or an empty array is regarded to be the
 *                       same as an array containing a single <code>null</code>
 * @param parameters     The actual arguments. The value at the placeholder position
 *                       will be ignored. Can be <code>null</code> if no parameter types
 *                       where given
 */
public CallbackClosure(Object callee, String callbackName, Class[] parameterTypes, Object[] parameters) {
    _callee = callee;

    if ((parameterTypes == null) || (parameterTypes.length == 0)) {
        _parameterTypes = new Class[] { null };
        _parameters = new Object[] { null };
        _callbackTypePos = 0;
    } else {
        _parameterTypes = new Class[parameterTypes.length];
        _parameters = new Object[parameterTypes.length];

        for (int idx = 0; idx < parameterTypes.length; idx++) {
            if (parameterTypes[idx] == null) {
                if (_callbackTypePos >= 0) {
                    throw new IllegalArgumentException("The parameter types may contain null only once");
                }
                _callbackTypePos = idx;
            } else {
                _parameterTypes[idx] = parameterTypes[idx];
                _parameters[idx] = parameters[idx];
            }
        }
        if (_callbackTypePos < 0) {
            throw new IllegalArgumentException("The parameter types need to a null placeholder");
        }
    }

    Class type = callee.getClass();

    // we're caching the callbacks
    do {
        Method[] methods = type.getDeclaredMethods();

        if (methods != null) {
            for (int idx = 0; idx < methods.length; idx++) {
                Method method = methods[idx];
                Class[] paramTypes = methods[idx].getParameterTypes();

                method.setAccessible(true);
                if (method.getName().equals(callbackName) && typesMatch(paramTypes)) {
                    if (_callbacks.get(paramTypes[_callbackTypePos]) == null) {
                        _callbacks.put(paramTypes[_callbackTypePos], methods[idx]);
                    }
                }
            }
        }
        type = type.getSuperclass();
    } while ((type != null) && !type.equals(Object.class));
}

From source file:cz.jirutka.validator.collection.internal.AnnotationUtils.java

/**
 * Creates instance (proxy) of the specified annotation with the given
 * attributes.//  ww w  . ja v  a 2  s  .  co m
 *
 * @param annotationType The annotation's class.
 * @param attributes A map with attribute values for the annotation to be created.
 * @param <T> The type of the annotation.
 *
 * @return An instance of the annotation.
 * @throws IllegalArgumentException if some attribute has wrong type or
 *         a required attribute is missing.
 */
public static <T extends Annotation> T createAnnotation(Class<T> annotationType,
        Map<String, Object> attributes) {

    // check if given attributes are defined in annotation
    for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext();) {
        String name = it.next();
        Object value = attributes.get(name);

        if (value == null) {
            LOG.warn("Attribute's value must not be null; will be ignored");
            it.remove();
            continue;
        }
        if (!hasAttribute(annotationType, name)) {
            LOG.warn("Annotation {} does not define attribute: {}; will be ignored", annotationType.getName(),
                    name);
            it.remove();
            continue;
        }
        Class<?> attrType = getAttributeType(annotationType, name);

        Validate.isTrue(isAssignable(value.getClass(), attrType),
                "Attribute '%s' expects %s, but given: %s (%s)", name, attrType.getName(), value,
                value.getClass().getName());
    }
    // check if required attributes are given
    for (Method m : annotationType.getDeclaredMethods()) {
        Validate.isTrue(attributes.containsKey(m.getName()) || m.getDefaultValue() != null,
                "Missing required attribute: %s", m.getName());
    }

    AnnotationDescriptor<T> descriptor = AnnotationDescriptor.getInstance(annotationType, attributes);

    return AnnotationFactory.create(descriptor);
}

From source file:com.googlecode.loosejar.ClassLoaderAnalyzer.java

private Method findMethod(Class<?> clazz, String name, Class<?>[] paramTypes) {
    Class<?> type = clazz;
    while (!Object.class.equals(type) && type != null) {
        Method[] methods = type.getDeclaredMethods();
        for (Method method : methods) {
            if (name.equals(method.getName()) && Arrays.equals(paramTypes, method.getParameterTypes())) {
                return method;
            }//  w ww . ja va 2 s  .c  o  m
        }
        type = type.getSuperclass();
    }
    return null;
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    final Class fclz = clz;
    Method[] result = (Method[]) declaredMethodCache.get(fclz);
    if (result != null) {
        return result;
    }// w w w .j a v a 2  s .  com

    // We have to raise privilege for getDeclaredMethods
    result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                return fclz.getDeclaredMethods();

            } catch (SecurityException ex) {
                // this means we're in a limited security environment
                // so let's try going through the public methods
                // and null those those that are not from the declaring
                // class
                Method[] methods = fclz.getMethods();
                for (int i = 0, size = methods.length; i < size; i++) {
                    Method method = methods[i];
                    if (!(fclz.equals(method.getDeclaringClass()))) {
                        methods[i] = null;
                    }
                }
                return methods;
            }
        }
    });

    // Null out any non-public methods.
    for (int i = 0; i < result.length; i++) {
        Method method = result[i];
        if (method != null) {
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
    }

    // Add it to the cache.
    declaredMethodCache.put(clz, result);
    return result;
}