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:com.helpinput.core.Utils.java

@SuppressWarnings("rawtypes")
public static Member findMember(Member[] methods, Class<?> targetClass, String methodName,
        Class<?>[] argsClasses) {
    for (Member member : methods) {
        if (!hasLength(methodName) || member.getName().equals(methodName)) {

            if (!hasLength(argsClasses))
                return setAccess(member);

            Class<?>[] paramTypes;

            if (member instanceof Method)
                paramTypes = ((Method) member).getParameterTypes();
            else//from w  w w. j  a v a 2 s. com
                paramTypes = ((Constructor) member).getParameterTypes();

            if (!hasLength(paramTypes) && !hasLength(argsClasses))
                return setAccess(member);

            if (argsClasses.length <= paramTypes.length) {
                for (int i = 0; i < argsClasses.length; i++) {
                    if (argsClasses[i] == null)
                        continue;

                    if (paramTypes[i].isPrimitive()) {
                        if (!primitiveWrap(paramTypes[i]).isAssignableFrom(argsClasses[i]))
                            break;
                    } else if (!paramTypes[i].isAssignableFrom(argsClasses[i]))
                        break;

                    if (i == argsClasses.length - 1) {
                        return setAccess(member);
                    }
                }
            }
        }
    }
    Class<?> superClass;
    if ((superClass = targetClass.getSuperclass()) != null) {
        return findMember(superClass.getDeclaredMethods(), superClass, methodName, argsClasses);
    }
    return null;
}

From source file:com.amalto.core.metadata.ClassRepository.java

private static Method[] getMethods(Class clazz) {
    // TMDM-5851: Work around several issues in introspection (getDeclaredMethods() and getMethods() may return
    // inherited methods if returned type is a sub class of super class method).
    Map<String, Class<?>> superClassMethods = new HashMap<String, Class<?>>();
    if (clazz.getSuperclass() != null) {
        for (Method method : clazz.getSuperclass().getMethods()) {
            superClassMethods.put(method.getName(), method.getReturnType());
        }/* ww w . j  ava  2 s  .c  om*/
    }
    Map<String, Method> methods = new HashMap<String, Method>();
    for (Method method : clazz.getDeclaredMethods()) {
        if (!(superClassMethods.containsKey(method.getName())
                && superClassMethods.get(method.getName()).equals(method.getReturnType()))) {
            methods.put(method.getName(), method);
        }
    }
    Method[] allMethods = clazz.getMethods();
    for (Method method : allMethods) {
        if (!methods.containsKey(method.getName())) {
            methods.put(method.getName(), method);
        }
    }
    Method[] classMethods = methods.values().toArray(new Method[methods.size()]);
    // TMDM-5483: getMethods() does not always return methods in same order: sort them to ensure fixed order.
    Arrays.sort(classMethods, new Comparator<Method>() {
        @Override
        public int compare(Method method1, Method method2) {
            return method1.getName().compareTo(method2.getName());
        }
    });
    return classMethods;
}

From source file:org.opentides.util.CrudUtil.java

/**
 * Helper method to retrieve all methods of a class including
 * methods declared in its superclass./* w  w  w .  j  a  v  a 2 s  . co m*/
 * @param clazz
 * @param includeParent
 * @return
 */
@SuppressWarnings({ "rawtypes" })
public static List<Method> getAllMethods(Class clazz, boolean includeParent) {
    List<Method> methods = new ArrayList<Method>();
    if (BaseEntity.class.isAssignableFrom(clazz) && includeParent)
        methods.addAll(getAllMethods(clazz.getSuperclass(), includeParent));
    for (Method method : clazz.getDeclaredMethods())
        methods.add(method);
    return methods;
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private static void traverseFieldsAndMethods(Class type, boolean fields, boolean methods,
        GatherFieldOrMethodInfoAction action) {
    List<AccessibleObject> fOms = new ArrayList<AccessibleObject>();
    if (fields) {
        fOms.addAll(Arrays.asList(type.getDeclaredFields()));
    }//from w w  w .j av a  2 s.co m
    if (methods) {
        fOms.addAll(Arrays.asList(type.getDeclaredMethods()));
    }

    for (AccessibleObject fOm : fOms) {
        if (fOm.isAnnotationPresent(Transient.class)) {
            continue;
        }

        action.gatherInfo(fOm);
    }
}

From source file:io.coala.json.DynaBean.java

/**
 * @param referenceType/*  w  w  w  .j ava  2 s  .  co m*/
 * @param <S>
 * @param <T>
 * @return
 */
static final <S, T> JsonDeserializer<T> createJsonDeserializer(final ObjectMapper om, final Class<T> resultType,
        final Properties... imports) {
    return new JsonDeserializer<T>() {

        @Override
        public T deserializeWithType(final JsonParser jp, final DeserializationContext ctxt,
                final TypeDeserializer typeDeserializer) throws IOException, JsonProcessingException {
            return deserialize(jp, ctxt);
        }

        @Override
        public T deserialize(final JsonParser jp, final DeserializationContext ctxt)
                throws IOException, JsonProcessingException {
            if (jp.getCurrentToken() == JsonToken.VALUE_NULL)
                return null;

            //            if( Wrapper.class.isAssignableFrom( resultType ) )
            //            {
            //               // FIXME
            //               LOG.trace( "deser wrapper intf of {}", jp.getText() );
            //               return (T) Wrapper.Util.valueOf( jp.getText(),
            //                     resultType.asSubclass( Wrapper.class ) );
            //            } 
            if (Config.class.isAssignableFrom(resultType)) {
                final Map<String, Object> entries = jp.readValueAs(new TypeReference<Map<String, Object>>() {
                });

                final Iterator<Entry<String, Object>> it = entries.entrySet().iterator();
                for (Entry<String, Object> next = null; it.hasNext(); next = it.next())
                    if (next != null && next.getValue() == null) {
                        LOG.trace("Ignoring null value: {}", next);
                        it.remove();
                    }
                return resultType.cast(ConfigFactory.create(resultType.asSubclass(Config.class), entries));
            }
            // else if (Config.class.isAssignableFrom(resultType))
            // throw new JsonGenerationException(
            // "Config does not extend "+Mutable.class.getName()+" required for deserialization: "
            // + Arrays.asList(resultType
            // .getInterfaces()));

            // can't parse directly to interface type
            final DynaBean bean = new DynaBean();
            final TreeNode tree = jp.readValueAsTree();

            // override attributes as defined in interface getters
            final Set<String> attributes = new HashSet<>();
            for (Method method : resultType.getMethods()) {
                if (method.getReturnType().equals(Void.TYPE) || method.getParameterTypes().length != 0)
                    continue;

                final String attribute = method.getName();
                if (attribute.equals("toString") || attribute.equals("hashCode"))
                    continue;

                attributes.add(attribute);
                final TreeNode value = tree.get(attribute);// bean.any().get(attributeName);
                if (value == null)
                    continue;

                bean.set(method.getName(),
                        om.treeToValue(value, JsonUtil.checkRegistered(om, method.getReturnType(), imports)));
            }
            if (tree.isObject()) {
                // keep superfluous properties as TreeNodes, just in case
                final Iterator<String> fieldNames = tree.fieldNames();
                while (fieldNames.hasNext()) {
                    final String fieldName = fieldNames.next();
                    if (!attributes.contains(fieldName))
                        bean.set(fieldName, tree.get(fieldName));
                }
            } else if (tree.isValueNode()) {
                for (Class<?> type : resultType.getInterfaces())
                    for (Method method : type.getDeclaredMethods()) {
                        //                     LOG.trace( "Scanning {}", method );
                        if (method.isAnnotationPresent(JsonProperty.class)) {
                            final String property = method.getAnnotation(JsonProperty.class).value();
                            //                        LOG.trace( "Setting {}: {}", property,
                            //                              ((ValueNode) tree).textValue() );
                            bean.set(property, ((ValueNode) tree).textValue());
                        }
                    }
            } else
                throw ExceptionFactory.createUnchecked("Expected {} but parsed: {}", resultType,
                        tree.getClass());

            return DynaBean.proxyOf(om, resultType, bean, imports);
        }
    };
}

From source file:org.apache.sling.contextaware.config.impl.metadata.AnnotationClassParser.java

/**
 * Build configuration metadata by parsing the given annotation interface class and it's configuration annotations.
 * @param clazz Configuration annotation class
 * @return Configuration metadata/*from ww  w  .  j av  a  2s . c om*/
 */
public static ConfigurationMetadata buildConfigurationMetadata(Class<?> clazz) {
    Configuration configAnnotation = clazz.getAnnotation(Configuration.class);
    if (configAnnotation == null) {
        throw new IllegalArgumentException("Class has not @Configuration annotation: " + clazz.getName());
    }

    // configuration metadata
    String configName = getConfigurationName(clazz, configAnnotation);
    ConfigurationMetadata configMetadata = new ConfigurationMetadata(configName);
    configMetadata.setLabel(emptyToNull(configAnnotation.label()));
    configMetadata.setDescription(emptyToNull(configAnnotation.description()));
    configMetadata.setProperties(propsArrayToMap(configAnnotation.property()));

    // property metadata
    Map<String, PropertyMetadata<?>> propertyMetadataList = new HashMap<>();
    Method[] propertyMethods = clazz.getDeclaredMethods();
    for (Method propertyMethod : propertyMethods) {
        PropertyMetadata<?> propertyMetadata = buildPropertyMetadata(propertyMethod,
                propertyMethod.getReturnType());
        propertyMetadataList.put(propertyMetadata.getName(), propertyMetadata);
    }
    configMetadata.setPropertyMetadata(propertyMetadataList);

    return configMetadata;
}

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

/**
 * This variant retrieves {@link Class#getDeclaredMethods()} from a local
 * cache in order to avoid the JVM's SecurityManager check and defensive
 * array copying. In addition, it also includes Java 8 default methods from
 * locally implemented interfaces, since those are effectively to be treated
 * just like declared methods.//from  ww  w.  j  a v  a2  s.c om
 * 
 * @param clazz
 *            the class to introspect
 * @return the cached array of methods
 * @see Class#getDeclaredMethods()
 */
private static Method[] getDeclaredMethods(Class<?> clazz) {
    Method[] result = declaredMethodsCache.get(clazz);
    if (result == null) {
        Method[] declaredMethods = clazz.getDeclaredMethods();
        List<Method> defaultMethods = findConcreteMethodsOnInterfaces(clazz);
        if (defaultMethods != null) {
            result = new Method[declaredMethods.length + defaultMethods.size()];
            System.arraycopy(declaredMethods, 0, result, 0, declaredMethods.length);
            int index = declaredMethods.length;
            for (Method defaultMethod : defaultMethods) {
                result[index] = defaultMethod;
                index++;
            }
        } else {
            result = declaredMethods;
        }
        declaredMethodsCache.put(clazz, (result.length == 0 ? NO_METHODS : result));
    }
    return result;
}

From source file:framework.GlobalHelpers.java

private static Action findActionOnProduction(String className, String action) {
    // use reflectasm for fast relection
    try {//from   ww  w  .j  a  v  a 2  s .  c  o  m
        Action cached = actionsCache.get(className, action);
        if (cached != null) {
            return cached;
        } else {
            Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
            MethodAccess access = MethodAccess.get(clazz);
            int index = access.getIndex(action);
            Method actionMethod = clazz.getDeclaredMethods()[index];
            Action instance = new Action(action, getControllerInstance(clazz), actionMethod, access, index);
            actionsCache.put(className, action, instance);
            return instance;
        }
    } catch (IllegalArgumentException e) {
        actionsCache.put(className, action, new Action(className, action));
        return null;
    } catch (ClassNotFoundException e) {
        actionsCache.put(className, action, new Action(className, action));
        return null;
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:gov.nih.nci.system.web.util.RESTUtil.java

/**
 * Gets all the methods for a given class
 *
 * @param resultClass/*  ww  w .j  a v  a  2 s .co m*/
 *            - Specifies the class name
 * @return - Returns all the methods
 */
@SuppressWarnings({ "rawtypes" })
public static Method[] getAllMethods(Class resultClass) {
    List<Method> methodList = new ArrayList<Method>();
    try {
        while (resultClass != null && !resultClass.isInterface() && !resultClass.isPrimitive()) {
            Method[] method = resultClass.getDeclaredMethods();
            for (int i = 0; i < method.length; i++) {
                method[i].setAccessible(true);
                methodList.add(method[i]);
            }
            if (!resultClass.getSuperclass().getName().equalsIgnoreCase("java.lang.Object")) {
                resultClass = resultClass.getSuperclass();
            } else {
                break;
            }
        }
    } catch (Exception ex) {
        log.error("ERROR: " + ex.getMessage());
    }
    Method[] methods = new Method[methodList.size()];
    for (int i = 0; i < methodList.size(); i++) {
        methods[i] = methodList.get(i);
    }
    return methods;
}

From source file:com.mycompany.selenium.factory.Page.java

public void takeAction(String action, Object... param) throws Throwable {
    action = action.replaceAll(" ", "_");
    try {// w w w  . j a v  a 2 s  .c  o  m
        MethodUtils.invokeMethod(this, action, param);
    } catch (NoSuchMethodException e) {
        StringBuilder sb = new StringBuilder();

        sb.append("There is no \"").append(action).append("\" action ").append("in ").append(this.getTitle())
                .append(" page object").append("\n");
        sb.append("Possible actions are:").append("\n");
        Class tClass = this.getClass();
        Method[] methods = tClass.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            sb.append("\t\"").append(this.getTitle()).append("\"->\"").append(methods[i].getName())
                    .append("\" with ").append(methods[i].getGenericParameterTypes().length)
                    .append(" input parameters").append("\n");
        }
        throw new NoSuchMethodException(sb.toString());
    } catch (InvocationTargetException ex) {
        throw ex.getCause();
    }
}