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:JavaFiles.AbstractWsToolClient.java

/** Generate a string containing the values of the fields with "get" methods. 
 * /*w ww.j a v  a  2 s . c  o  m*/
 * @param obj Object the get values from
 * @return String containing values and method names.
 */
// @SuppressWarnings("unchecked")
protected String objectFieldsToString(Object obj) {
    printDebugMessage("ObjectFieldsToString", "Begin", 31);
    StringBuilder strBuilder = new StringBuilder();
    try {
        Class objType = obj.getClass();
        printDebugMessage("ObjectFieldsToString", "objType: " + objType, 32);
        java.lang.reflect.Method[] methods = objType.getMethods();
        for (int i = 0; i < methods.length; i++) {
            String methodName = methods[i].getName();
            if (methodName.startsWith("get") && methods[i].getParameterTypes().length == 0
                    && !methodName.equals("getClass") && !methodName.equals("getTypeDesc")) {
                printDebugMessage("ObjectFieldsToString", "invoke(): " + methodName, 32);
                Object tmpObj = methods[i].invoke(obj, new Object[0]);
                // Handle any string lists (e.g. database)
                if (tmpObj instanceof String[]) {
                    String[] tmpList = (String[]) tmpObj;
                    strBuilder.append(methodName + ":\n");
                    for (int j = 0; j < tmpList.length; j++) {
                        strBuilder.append("\t" + tmpList[j] + "\n");
                    }
                }
                // Otherwise just use implicit toString();
                else {
                    strBuilder.append(methodName + ": " + tmpObj + "\n");
                }
            }
        }
    } catch (SecurityException e) {
        System.err.println(e.getMessage());
    } catch (IllegalArgumentException e) {
        System.err.println(e.getMessage());
    } catch (IllegalAccessException e) {
        System.err.println(e.getMessage());
    } catch (InvocationTargetException e) {
        System.err.println(e.getMessage());
    }
    printDebugMessage("ObjectFieldsToString", "End", 31);
    return strBuilder.toString();
}

From source file:org.openmrs.module.privilegehelper.PrivilegeLogger.java

/**
 * Inspects the stack trace to find a place where the privilege was checked
 * // w ww  .j av a 2  s .  c  o m
 * @return the class.method or <code>null</code> if it cannot be found
 */
private StackTraceInfo inspectStackTrace() {
    final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
    boolean requiredPrivilege = false;
    for (int i = 0; i < stackTrace.length; i++) {
        final StackTraceElement unrelatedElement = stackTrace[i];

        if (UserContext.class.getName().equals(unrelatedElement.getClassName())
                && "hasPrivilege".equals(unrelatedElement.getMethodName())) {

            for (int j = i + 1; j < stackTrace.length; j++) {
                final StackTraceElement element = stackTrace[j];

                if (element.getFileName() != null && element.getFileName().endsWith("_jsp")) {
                    String jsp = element.getFileName();
                    int indexOfView = jsp.indexOf("view");
                    if (indexOfView > 0) {
                        jsp = jsp.substring(indexOfView);
                    }
                    jsp = jsp.replace(".", "/");
                    jsp = jsp.replace("_", ".");

                    return new StackTraceInfo(jsp, requiredPrivilege);
                }

                if (!element.getClassName().startsWith("org.openmrs")) {
                    continue;
                }

                //Determine if it is a required privilege or a simple check
                if (RequireTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (PrivilegeTag.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = false;
                    continue;
                }
                if (AuthorizationAdvice.class.getName().equals(element.getClassName())) {
                    requiredPrivilege = true;
                    continue;
                }
                if (Context.class.getName().equals(element.getClassName())) {
                    if ("requirePrivilege".equals(element.getMethodName())) {
                        requiredPrivilege = true;
                    }
                    continue;
                }

                try {
                    final Class<?> clazz = OpenmrsClassLoader.getInstance().loadClass(element.getClassName());

                    if (clazz.isAnnotationPresent(Controller.class)) {
                        String url = "";

                        final RequestMapping clazzRequestMapping = clazz.getAnnotation(RequestMapping.class);
                        if (clazzRequestMapping != null) {
                            url = clazzRequestMapping.value()[0];
                        }

                        final Method[] methods = clazz.getMethods();
                        for (Method method : methods) {
                            if (method.getName().equals(element.getMethodName())) {
                                final RequestMapping requestMapping = method
                                        .getAnnotation(RequestMapping.class);
                                if (requestMapping != null) {
                                    url += requestMapping.value()[0];
                                }
                                break;
                            }
                        }

                        if (url.isEmpty()) {
                            return new StackTraceInfo(element.toString(), requiredPrivilege);
                        } else {
                            return new StackTraceInfo(element.toString() + ", URL: " + url, requiredPrivilege);
                        }
                    }
                } catch (ClassNotFoundException e) {
                }

                return new StackTraceInfo(element.toString(), requiredPrivilege);
            }
        }
    }
    return null;
}

From source file:com.m4rc310.cb.builders.ComponentBuilder.java

@Override
public List getTargetsForMethodName(String methodName) {
    Collection<Method> methods = new ArrayList<>();
    List ret = new ArrayList();

    if (methodName.isEmpty()) {
        return ret;
    }/*from  w  w  w  . ja v  a  2  s .co  m*/

    for (Object tar : getAllTargets()) {
        Class tarClass = tar.getClass();

        methods.addAll(Arrays.asList(tarClass.getDeclaredMethods()));
        methods.addAll(Arrays.asList(tarClass.getMethods()));

        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                if (!ret.contains(tar)) {
                    ret.add(tar);
                    break;
                }
            }
        }
    }

    return ret;
}

From source file:com.espertech.esper.epl.core.EngineImportServiceImpl.java

public Method resolveMethod(String className, String methodName) throws EngineImportException {
    Class clazz;
    try {/*from  w ww  . j av  a2  s . c o m*/
        clazz = resolveClassInternal(className, false);
    } catch (ClassNotFoundException e) {
        throw new EngineImportException(
                "Could not load class by name '" + className + "', please check imports", e);
    }

    Method methods[] = clazz.getMethods();
    Method methodByName = null;

    // check each method by name
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            if (methodByName != null) {
                throw new EngineImportException("Ambiguous method name: method by name '" + methodName
                        + "' is overloaded in class '" + className + "'");
            }
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers)) {
                methodByName = method;
            }
        }
    }

    if (methodByName == null) {
        throw new EngineImportException(
                "Could not find static method named '" + methodName + "' in class '" + className + "'");
    }
    return methodByName;
}

From source file:org.traccar.database.QueryBuilder.java

public <T> Collection<T> executeQuery(Class<T> clazz) throws SQLException {
    List<T> result = new LinkedList<>();

    if (query != null) {

        try {/*from  w w w .j a  v  a2  s  . co  m*/

            try (ResultSet resultSet = statement.executeQuery()) {

                ResultSetMetaData resultMetaData = resultSet.getMetaData();

                List<ResultSetProcessor<T>> processors = new LinkedList<>();

                Method[] methods = clazz.getMethods();

                for (final Method method : methods) {
                    if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                            && !method.isAnnotationPresent(QueryIgnore.class)) {

                        final String name = method.getName().substring(3);

                        // Check if column exists
                        boolean column = false;
                        for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
                            if (name.equalsIgnoreCase(resultMetaData.getColumnLabel(i))) {
                                column = true;
                                break;
                            }
                        }
                        if (!column) {
                            continue;
                        }

                        addProcessors(processors, method.getParameterTypes()[0], method, name);
                    }
                }

                while (resultSet.next()) {
                    try {
                        T object = clazz.newInstance();
                        for (ResultSetProcessor<T> processor : processors) {
                            processor.process(object, resultSet);
                        }
                        result.add(object);
                    } catch (InstantiationException | IllegalAccessException e) {
                        throw new IllegalArgumentException();
                    }
                }
            }

        } finally {
            statement.close();
            connection.close();
        }
    }

    return result;
}

From source file:io.renren.modules.test.jmeter.report.LocalReportGenerator.java

private void addGraphConsumer(FilterConsumer nameFilter, FilterConsumer excludeControllerFilter,
        Map.Entry<String, GraphConfiguration> entryGraphCfg) throws GenerationException {
    String graphName = entryGraphCfg.getKey();
    GraphConfiguration graphConfiguration = entryGraphCfg.getValue();

    // Instantiate the class from the classname
    String className = graphConfiguration.getClassName();
    try {/* w  ww. ja v a2s.  co  m*/
        Class<?> clazz = Class.forName(className);
        Object obj = clazz.newInstance();
        AbstractGraphConsumer graph = (AbstractGraphConsumer) obj;
        graph.setName(graphName);

        // Set the graph title
        graph.setTitle(graphConfiguration.getTitle());

        // Set graph properties using reflection
        Method[] methods = clazz.getMethods();
        for (Map.Entry<String, String> entryProperty : graphConfiguration.getProperties().entrySet()) {
            String propertyName = entryProperty.getKey();
            String propertyValue = entryProperty.getValue();
            String setterName = getSetterName(propertyName);

            setProperty(className, obj, methods, propertyName, propertyValue, setterName);
        }

        // Choose which entry point to use to plug the graph
        AbstractSampleConsumer entryPoint = graphConfiguration.excludesControllers() ? excludeControllerFilter
                : nameFilter;
        entryPoint.addSampleConsumer(graph);
    } catch (ClassNotFoundException | IllegalAccessException | InstantiationException | ClassCastException ex) {
        String error = String.format(INVALID_CLASS_FMT, className);
        log.error(error, ex);
        throw new GenerationException(error, ex);
    }
}

From source file:com.mycila.plugin.Cglib2AopProxy.java

/**
 * Checks for final methods on the <code>Class</code> and writes warnings to the log
 * for each one found.//  w  w w .j a  v a2s. c  om
 */
private void doValidateClass(Class proxySuperClass) {
    Method[] methods = proxySuperClass.getMethods();
    for (Method method : methods) {
        if (!Object.class.equals(method.getDeclaringClass()) && Modifier.isFinal(method.getModifiers())) {
            logger.warn("Unable to proxy method [" + method + "] because it is final: "
                    + "All calls to this method via a proxy will be routed directly to the proxy.");
        }
    }
}

From source file:org.openmrs.module.webservices.rest.web.resource.impl.BaseDelegatingResource.java

/**
 * Finds a method on clazz or a superclass that is annotated with {@link RepHandler} and is
 * suitable for rep//from w  w  w .  j ava  2s .com
 * 
 * @param clazz
 * @param rep
 * @return
 */
private Method findAnnotatedMethodForRepresentation(Class<?> clazz, Representation rep) {
    for (Method method : clazz.getMethods()) {
        RepHandler ann = method.getAnnotation(RepHandler.class);
        if (ann != null) {
            if (ann.name().equals(rep.getRepresentation()))
                return method;
            if (ann.value().isAssignableFrom(rep.getClass()))
                return method;
        }
    }
    return null;
}

From source file:com.dungnv.vfw5.base.service.BaseFWServiceImpl.java

@Override
public List prepareCondition(TDTO tForm) {
    List<ConditionBean> lstCondition = new ArrayList<ConditionBean>();
    if (tForm == null) {
        return lstCondition;
    }//w ww . ja v a  2 s.co  m
    Method methods[] = tForm.toModel().getClass().getDeclaredMethods();
    Method methodForms[] = tForm.getClass().getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        if (ReflectUtils.isGetter(methods[i])) {
            try {
                Object value = methods[i].invoke(tForm.toModel());
                String returnType = methods[i].getReturnType().getSimpleName().toUpperCase();
                if (value == null || "".equals(value)) {
                    if (ParamUtils.TYPE_NUMBER.indexOf(returnType) >= 0) {
                        try {
                            Column column = methods[i].getAnnotation(Column.class);
                            if (StringUtils.validString(column.columnDefinition())) {
                                String colId = "";
                                String colName = "";
                                for (int j = 0; j < methodForms.length; j++) {
                                    if (methodForms[j].getName().equals(methods[i].getName() + "Name")) {
                                        value = methodForms[j].invoke(tForm);
                                        if (!StringUtils.validString(value)) {
                                            break;
                                        }
                                        Class cl = Class.forName("com.dungnv.ra.database.BO."
                                                + column.columnDefinition() + "BO");
                                        Constructor ct = cl.getConstructor();
                                        Object obj = ct.newInstance();
                                        Method mtd[] = cl.getMethods();
                                        for (int k = 0; k < mtd.length; k++) {
                                            if (mtd[k].getName().equals("getColId")) {
                                                colId = mtd[k].invoke(obj).toString();
                                            }
                                            if (mtd[k].getName().equals("getColName")) {
                                                colName = mtd[k].invoke(obj).toString();
                                            }
                                        }
                                        break;
                                    }
                                }
                                if (StringUtils.validString(value)) {
                                    lstCondition
                                            .add(new ConditionBean(ReflectUtils.getColumnBeanName(methods[i]),
                                                    ParamUtils.OP_IN,
                                                    BaseFWDAOImpl.genSubQuery(column.columnDefinition(), colId,
                                                            colName, value.toString()),
                                                    ParamUtils.TYPE_NUMBER));
                                }
                            }
                        } catch (Exception e) {
                            System.out.println("PrepareCondition Error: " + e.getMessage());
                        }
                    }
                } else if (ParamUtils.TYPE_STRING.indexOf(returnType) >= 0) {
                    if (!value.equals(String.valueOf(ParamUtils.DEFAULT_VALUE))) {
                        String stringValue = value.toString();
                        String opCompare = ParamUtils.OP_LIKE;
                        String valueCompare = StringUtils.formatLike(stringValue);
                        Column column = methods[i].getAnnotation(Column.class);
                        if (StringUtils.validString(column.columnDefinition())
                                && column.columnDefinition().equals("param")) {
                            opCompare = ParamUtils.OP_EQUAL;
                            valueCompare = stringValue.toLowerCase(Locale.ENGLISH);
                        }
                        if (!stringValue.trim().equals("")) {
                            lstCondition.add(new ConditionBean(
                                    StringUtils.formatFunction("lower",
                                            ReflectUtils.getColumnBeanName(methods[i])),
                                    opCompare, valueCompare, ParamUtils.TYPE_STRING));
                        }
                    }
                } else if (ParamUtils.TYPE_NUMBER.indexOf(returnType) >= 0) {
                    if (!value.toString().equals(String.valueOf(ParamUtils.DEFAULT_VALUE))) {
                        lstCondition.add(new ConditionBean(ReflectUtils.getColumnBeanName(methods[i]),
                                ParamUtils.OP_EQUAL, value.toString(), ParamUtils.TYPE_NUMBER));
                    }
                } else if (ParamUtils.TYPE_DATE.indexOf(returnType) >= 0) {
                    Date dateValue = (Date) value;
                    String methodName = methods[i].getName();
                    String operator = ParamUtils.OP_EQUAL;
                    if (methodName.indexOf("From") >= 0 || methodName.indexOf("Begin") >= 0
                            || methodName.indexOf("Sta") >= 0) {
                        operator = ParamUtils.OP_GREATER_EQUAL;
                    } else if (methodName.indexOf("To") >= 0 || methodName.indexOf("End") >= 0
                            || methodName.indexOf("Last") >= 0) {
                        operator = ParamUtils.OP_LESS_EQUAL;
                    }
                    lstCondition.add(new ConditionBean(
                            StringUtils.formatFunction("trunc", ReflectUtils.getColumnBeanName(methods[i])),
                            operator, StringUtils.formatDate(dateValue), ParamUtils.TYPE_DATE));
                }
            } catch (IllegalAccessException iae) {
                System.out.println("PrepareCondition Error: " + iae.getMessage());
            } catch (InvocationTargetException ite) {
                System.out.println("PrepareCondition Error: " + ite.getMessage());
            }
        }
    }
    return lstCondition;
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.FixedFormatManagerImpl.java

/**
 * @inheritDoc//w w  w. j a  va2s .c o  m
 */
public <T> T load(Class<T> fixedFormatRecordClass, String data) {
    HashMap<String, Object> foundData = new HashMap<String, Object>();
    HashMap<String, Class<?>> methodClass = new HashMap<String, Class<?>>();
    //assert the record is marked with a Record
    getAndAssertRecordAnnotation(fixedFormatRecordClass);

    //create instance to set data into
    T instance = createRecordInstance(fixedFormatRecordClass);

    //look for setter annotations and read data from the 'data' string
    Method[] allMethods = fixedFormatRecordClass.getMethods();
    for (Method method : allMethods) {
        String methodName = stripMethodPrefix(method.getName());
        Field fieldAnnotation = method.getAnnotation(Field.class);
        Fields fieldsAnnotation = method.getAnnotation(Fields.class);
        if (fieldAnnotation != null) {
            readFieldData(fixedFormatRecordClass, data, foundData, methodClass, method, methodName,
                    fieldAnnotation);
        } else if (fieldsAnnotation != null) {
            //assert that the fields annotation contains minimum one field anno
            if (fieldsAnnotation.value() == null || fieldsAnnotation.value().length == 0) {
                throw new FixedFormatException(format("%s annotation must contain minimum one %s annotation",
                        Fields.class.getName(), Field.class.getName()));
            }
            readFieldData(fixedFormatRecordClass, data, foundData, methodClass, method, methodName,
                    fieldsAnnotation.value()[0]);
        }
    }

    Set<String> keys = foundData.keySet();
    for (String key : keys) {
        String setterMethodName = "set" + key;

        Object foundDataObj = foundData.get(key);
        if (foundDataObj != null) {
            Class datatype = methodClass.get(key);
            Method method;
            try {
                method = fixedFormatRecordClass.getMethod(setterMethodName, datatype);
            } catch (NoSuchMethodException e) {
                throw new FixedFormatException(format("setter method named %s.%s(%s) does not exist",
                        fixedFormatRecordClass.getName(), setterMethodName, datatype));
            }
            try {
                method.invoke(instance, foundData.get(key));
            } catch (Exception e) {
                throw new FixedFormatException(format("could not invoke method %s.%s(%s)",
                        fixedFormatRecordClass.getName(), setterMethodName, datatype), e);
            }
        }

    }
    return instance;
}