Example usage for java.lang Class getMethods

List of usage examples for java.lang Class getMethods

Introduction

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

Prototype

@CallerSensitive
public Method[] getMethods() throws SecurityException 

Source Link

Document

Returns an array containing Method objects reflecting all the public methods of the class or interface represented by this Class object, including those declared by the class or interface and those inherited from superclasses and superinterfaces.

Usage

From source file:com.liferay.portal.jsonwebservice.JSONWebServiceConfigurator.java

private void _onJSONWebServiceClass(String className) throws Exception {
    Class<?> actionClass = _classLoader.loadClass(className);

    if (!_isJSONWebServiceClass(actionClass)) {
        return;//w  w w  .  j  a  v  a  2s . c  om
    }

    if (actionClass.isInterface() && _hasAnnotatedServiceImpl(className)) {
        return;
    }

    JSONWebService classAnnotation = actionClass.getAnnotation(JSONWebService.class);

    JSONWebServiceMode classAnnotationMode = JSONWebServiceMode.MANUAL;

    if (classAnnotation != null) {
        classAnnotationMode = classAnnotation.mode();
    }

    Method[] methods = actionClass.getMethods();

    for (Method method : methods) {
        Class<?> methodDeclaringClass = method.getDeclaringClass();

        if (!methodDeclaringClass.equals(actionClass)) {
            continue;
        }

        boolean registerMethod = false;

        JSONWebService methodAnnotation = method.getAnnotation(JSONWebService.class);

        if (classAnnotationMode.equals(JSONWebServiceMode.AUTO)) {
            registerMethod = true;

            if (methodAnnotation != null) {
                JSONWebServiceMode methodAnnotationMode = methodAnnotation.mode();

                if (methodAnnotationMode.equals(JSONWebServiceMode.IGNORE)) {

                    registerMethod = false;
                }
            }
        } else {
            if (methodAnnotation != null) {
                JSONWebServiceMode methodAnnotationMode = methodAnnotation.mode();

                if (!methodAnnotationMode.equals(JSONWebServiceMode.IGNORE)) {

                    registerMethod = true;
                }
            }
        }

        if (registerMethod) {
            _registerJSONWebServiceAction(actionClass, method);
        }
    }
}

From source file:com.grepcurl.random.ObjectGenerator.java

public <T> T generate(Class<T> klass) {
    Validate.notNull(klass);//from ww  w  .ja  va 2s. co  m
    if (verbose) {
        log(String.format("generating object of type: %s", klass));
    }
    try {
        Deque<Object> objectStack = new ArrayDeque<>();
        T t;
        if (klass.isEnum()) {
            int randomOrdinal = randomInt(0, klass.getEnumConstants().length - 1);
            t = klass.getEnumConstants()[randomOrdinal];
        } else {
            t = klass.getConstructor().newInstance();
        }
        objectStack.push(t);
        Method[] methods = klass.getMethods();
        for (Method method : methods) {
            _processMethod(method, null, t, objectStack);
        }
        objectStack.pop();
        return t;
    } catch (Exception e) {
        throw new FailedRandomObjectGenerationException(e);
    }
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private void deserializeWithCustomFieldDeserializer(Class<?> customSerializer, Class<?> instanceClass,
        Object instance) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    assert (!instanceClass.isArray());

    for (Method method : customSerializer.getMethods()) {
        if ("deserialize".equals(method.getName())) {
            method.invoke(null, this, instance);
            return;
        }//from w w w  . ja  v  a  2s . co  m
    }
    throw new NoSuchMethodException("deserialize");
}

From source file:io.milton.http.annotated.AnnotationResourceFactory.java

public java.lang.reflect.Method findMethodForAnno(Class sourceClass, Class annoClass) {
    for (java.lang.reflect.Method m : sourceClass.getMethods()) {
        Annotation a = m.getAnnotation(annoClass);
        if (a != null) {
            return m;
        }/*  ww  w.  ja v  a 2  s  .  co  m*/
    }
    return null;
}

From source file:com.reversemind.hypergate.server.PayloadProcessor.java

private Method findMethod(Class interfaceClass, String methodName, Object[] arguments) {
    Method selectedMethod = null;

    // Let's check that not all arguments are null
    int argumentsCount = 0;
    for (int i = 0; i < arguments.length; i++) {
        if (arguments[i] == null) {
            argumentsCount++;//  www  . ja  v  a 2s . c  o m
        }
    }

    boolean argumentsAreNull = false;

    if (argumentsCount == arguments.length) {
        LOG.info("Not all arguments are null");
        argumentsAreNull = true;
    }

    Method[] pojoClassMethods = interfaceClass.getMethods();
    String compareTypeName = "";
    for (Method method : pojoClassMethods) {

        if (method.getName().equals(methodName)) {
            LOG.debug(method.getName() + " args:" + method.getParameterTypes().length);

            if (arguments.length == method.getParameterTypes().length) {

                if (arguments.length == 0) {
                    selectedMethod = method;
                    break;
                }

                if (argumentsAreNull) {
                    selectedMethod = method;
                    break;
                }

                if (method.getParameterTypes().length > 0) {
                    int count = arguments.length;
                    Class[] cl = method.getParameterTypes();
                    for (int i = 0; i < arguments.length; i++) {

                        compareTypeName = cl[i].getCanonicalName();
                        if (typeMap.containsKey(cl[i].getCanonicalName())) {
                            compareTypeName = typeMap.get(cl[i].getCanonicalName()).getCanonicalName();
                        }

                        LOG.debug("arguments[i]:" + arguments[i]);
                        if (arguments[i] != null) {
                            LOG.debug("arguments[i].getClass():" + arguments[i].getClass());
                            LOG.debug("arguments[i].getClass().getCanonicalName():"
                                    + arguments[i].getClass().getCanonicalName());
                        }

                        if (arguments[i] == null) {
                            count--;
                        } else if (compareTypeName != null && arguments[i] != null
                                && compareTypeName.equals(arguments[i].getClass().getCanonicalName())) {
                            count--;
                        } else if (compareTypeName != null && arguments[i] != null
                                && arguments[i].getClass().getCanonicalName()
                                        .equals(ArrayList.class.getCanonicalName())
                                && compareTypeName.equals(List.class.getCanonicalName())) {
                            count--;
                        }

                    }

                    //                        Type[] tp = method.getGenericParameterTypes();
                    //                        for(int i=0; i< arguments.length; i++){
                    ////                            LOG.debug("generic type = " + i + " -- " + ((ParameterizedTypeImpl) tp[i]).getRawType());
                    //                            LOG.debug("generic type = " + i + " -- " + tp[i]);
                    //                        }

                    if (count == 0) {
                        selectedMethod = method;
                        break;
                    }
                }
            }
        }

        //            if (method.getName().equals(methodName)) {
        //                selectedMethod = method;
        //                LOG.info("Find method:" + selectedMethod);
        //                break;
        //            }
    }

    return selectedMethod;
}

From source file:com.strider.datadefender.DatabaseAnonymizer.java

/**
 * Calls the anonymization function for the given Column, and returns its
 * anonymized value./*  w  ww.j  a va  2 s . c  o  m*/
 * 
 * @param dbConn
 * @param row
 * @param column
 * @return
 * @throws NoSuchMethodException
 * @throws SecurityException
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException 
 */
private Object callAnonymizingFunctionWithoutParameters(final Connection dbConn, final Column column)
        throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {

    final String function = column.getFunction();
    if (function == null || function.equals("")) {
        log.warn("Function is not defined for column [" + column + "]. Moving to the next column.");
        return "";
    }

    try {
        final String className = Utils.getClassName(function);
        final String methodName = Utils.getMethodName(function);
        final Class<?> clazz = Class.forName(className);

        final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance();
        instance.setDatabaseConnection(dbConn);

        final Method[] methods = clazz.getMethods();
        Method selectedMethod = null;
        Object returnType = null;

        methodLoop: for (final Method m : methods) {
            //if (m.getName().equals(methodName) && m.getReturnType() == String.class) {
            if (m.getName().equals(methodName)) {
                log.debug("  Found method: " + m.getName());
                selectedMethod = m;
                returnType = m.getReturnType();
                break;
            }
        }

        if (selectedMethod == null) {
            final StringBuilder s = new StringBuilder("Anonymization method: ");
            s.append(methodName).append(") was not found in class ").append(className);
            throw new NoSuchMethodException(s.toString());
        }

        log.debug("Anonymizing function name: " + methodName);
        final Object anonymizedValue = selectedMethod.invoke(instance);
        log.debug("anonymizedValue " + anonymizedValue);
        if (anonymizedValue == null) {
            return null;
        }

        log.debug(returnType);
        if (returnType == String.class) {
            return anonymizedValue.toString();
        } else if (returnType == java.sql.Date.class) {
            return anonymizedValue;
        } else if ("int".equals(returnType)) {
            return anonymizedValue;
        }
    } catch (InstantiationException | ClassNotFoundException ex) {
        log.error(ex.toString());
    }

    return "";
}

From source file:ca.uhn.fhir.rest.client.RestfulClientFactory.java

/**
 * Instantiates a new client instance//from  ww w  . j  a va 2 s.  co m
 * 
 * @param theClientType
 *            The client type, which is an interface type to be instantiated
 * @param theServerBase
 *            The URL of the base for the restful FHIR server to connect to
 * @return A newly created client
 * @throws ConfigurationException
 *             If the interface type is not an interface
 */
@Override
public synchronized <T extends IRestfulClient> T newClient(Class<T> theClientType, String theServerBase) {
    validateConfigured();

    if (!theClientType.isInterface()) {
        throw new ConfigurationException(theClientType.getCanonicalName() + " is not an interface");
    }

    ClientInvocationHandlerFactory invocationHandler = myInvocationHandlers.get(theClientType);
    if (invocationHandler == null) {
        IHttpClient httpClient = getHttpClient(theServerBase);
        invocationHandler = new ClientInvocationHandlerFactory(httpClient, myContext, theServerBase,
                theClientType);
        for (Method nextMethod : theClientType.getMethods()) {
            BaseMethodBinding<?> binding = BaseMethodBinding.bindMethod(nextMethod, myContext, null);
            invocationHandler.addBinding(nextMethod, binding);
        }
        myInvocationHandlers.put(theClientType, invocationHandler);
    }

    T proxy = instantiateProxy(theClientType, invocationHandler.newInvocationHandler(this));

    return proxy;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

/**
 * Creates entity block//from  w  w  w. j av a 2 s .co m
 *
 * @param converterService converter manager
 * @param procedureInfo    procedure into
 * @param entityClass      entity class
 * @return block
 */
private IParametersSetterBlock createEntityBlock(ParameterConverterService converterService,
        StoredProcedureInfo procedureInfo, Class entityClass, final int[] nonListArgumentIndexes) {
    List<EntityArgumentGetter> getters = new LinkedList<EntityArgumentGetter>();
    for (Method getterMethod : entityClass.getMethods()) {
        if (getterMethod.isAnnotationPresent(Column.class)) {
            Column columnAnnotation = getterMethod.getAnnotation(Column.class);
            StoredProcedureArgumentInfo argumentInfo = procedureInfo.getArgumentInfo(columnAnnotation.name());
            if (argumentInfo == null) {
                throw new IllegalStateException("Column " + columnAnnotation.name() + " was not found in "
                        + procedureInfo.getProcedureName());
            }
            if (argumentInfo.getColumnType() == 1) {
                IParameterConverter paramConverter = converterService.getConverter(argumentInfo.getDataType(),
                        getterMethod.getReturnType());
                getters.add(new EntityArgumentGetter(getterMethod, paramConverter,
                        argumentInfo.getStatementArgument()));
            }
        } else if (getterMethod.isAnnotationPresent(OneToOne.class)
                || getterMethod.isAnnotationPresent(ManyToOne.class)) {

            if (getterMethod.isAnnotationPresent(JoinColumn.class)) {
                JoinColumn joinColumn = getterMethod.getAnnotation(JoinColumn.class);

                if (StringUtils.hasText(joinColumn.name())) {
                    StoredProcedureArgumentInfo argumentInfo = procedureInfo.getArgumentInfo(joinColumn.name());

                    if (argumentInfo == null) {
                        throw new IllegalStateException("Column " + joinColumn.name() + " was not found in "
                                + procedureInfo.getProcedureName());
                    }
                    getters.add(new EntityArgumentGetterOneToOneJoinColumn(getterMethod,
                            argumentInfo.getStatementArgument()));
                } else {
                    throw new IllegalStateException("@JoinColumn.name is empty for "
                            + entityClass.getSimpleName() + "." + getterMethod.getName() + "()");
                }
            } else {
                throw new IllegalStateException("No @JoinColumn annotation was found in "
                        + entityClass.getSimpleName() + "." + getterMethod.getName() + "()");
            }
        }
    }
    return new ParametersSetterBlockEntity(getters, nonListArgumentIndexes);
}

From source file:com.google.dart.java2dart.SyntaxTranslator.java

/**
 * Replaces "node" with "replacement" in parent of "node".
 *//* w ww.  j av a  2s . c o  m*/
public static void replaceNode(ASTNode parent, ASTNode node, ASTNode replacement) {
    Class<? extends ASTNode> parentClass = parent.getClass();
    // try get/set methods
    try {
        for (Method getMethod : parentClass.getMethods()) {
            String getName = getMethod.getName();
            if (getName.startsWith("get") && getMethod.getParameterTypes().length == 0
                    && getMethod.invoke(parent) == node) {
                String setName = "set" + getName.substring(3);
                Method setMethod = parentClass.getMethod(setName, getMethod.getReturnType());
                setMethod.invoke(parent, replacement);
                return;
            }
        }
    } catch (Throwable e) {
        ExecutionUtils.propagate(e);
    }
    // special cases
    if (parent instanceof ListLiteral) {
        List<Expression> elements = ((ListLiteral) parent).getElements();
        int index = elements.indexOf(node);
        if (index != -1) {
            elements.set(index, (Expression) replacement);
            return;
        }
    }
    if (parent instanceof ArgumentList) {
        List<Expression> arguments = ((ArgumentList) parent).getArguments();
        int index = arguments.indexOf(node);
        if (index != -1) {
            arguments.set(index, (Expression) replacement);
            return;
        }
    }
    if (parent instanceof TypeArgumentList) {
        List<TypeName> arguments = ((TypeArgumentList) parent).getArguments();
        int index = arguments.indexOf(node);
        if (index != -1) {
            arguments.set(index, (TypeName) replacement);
            return;
        }
    }
    // not found
    throw new UnsupportedOperationException("" + parentClass);
}

From source file:cn.webwheel.DefaultMain.java

@SuppressWarnings("unchecked")
private void autoMap(String root, String pkg, String name) {
    Class cls;
    try {/*from  w  w  w .j  av  a 2s .  com*/
        cls = Class.forName(pkg + "." + name);
    } catch (ClassNotFoundException e) {
        return;
    }
    if (cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers())) {
        return;
    }
    if (cls.isAnonymousClass() || cls.isLocalClass() || !Modifier.isPublic(cls.getModifiers())
            || Modifier.isAbstract(cls.getModifiers())) {
        return;
    }

    name = name.replace('$', '.');

    for (Method method : cls.getMethods()) {

        String pathPrefix = pkg.substring(root.length()).replace('.', '/') + '/';
        String path = pathPrefix + name + '.' + method.getName();

        Action action = getAction(cls, method);
        if (action == null)
            continue;

        if (!action.value().isEmpty()) {
            if (action.value().startsWith("?")) {
                path = path + action.value();
            } else if (action.value().startsWith(".")) {
                path = pathPrefix + name + action.value();
            } else if (!action.value().startsWith("/")) {
                path = pathPrefix + action.value();
            } else {
                path = action.value();
            }
        }
        ActionBinder binder = map(path);
        if (!action.rest().isEmpty()) {
            String rest = action.rest();
            if (!rest.startsWith("/"))
                rest = pathPrefix + rest;
            binder = binder.rest(rest);
        }
        SetterConfig cfg = binder.with(cls, method);
        if (!action.charset().isEmpty()) {
            cfg = cfg.setCharset(action.charset());
        }
        if (action.fileUploadFileSizeMax() != 0) {
            cfg = cfg.setFileUploadFileSizeMax(action.fileUploadFileSizeMax());
        }
        if (action.fileUploadSizeMax() != 0) {
            cfg.setFileUploadSizeMax(action.fileUploadSizeMax());
        }
        if (action.setterPolicy() != SetterPolicy.Auto) {
            cfg.setSetterPolicy(action.setterPolicy());
        }
    }
}