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:lu.softec.xwiki.macro.internal.ClassRunnerMacro.java

protected String execute(ClassLoader loader, String className, ClassRunnerMacroParameters parameters,
        Object xcontext) throws MacroExecutionException {
    StringWriter stringWriter = new StringWriter();
    boolean hasArgs = (parameters.getRawProperties() != null);
    Map<String, Object> args = (hasArgs) ? parameters.getRawProperties() : new LinkedHashMap<String, Object>();

    Class<?> klass;
    try {/*from ww w . j a va  2  s . c  o m*/
        klass = loader.loadClass(className);
    } catch (ClassNotFoundException e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    Method[] methods = klass.getMethods();
    Method run1 = null;
    Method run2 = null;
    Method run3 = null;
    Method setContext1 = null;
    Method setContext2 = null;
    Method getParser = null;
    for (Method m : methods) {
        if (m.getName().equals("run")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(stringWriter.getClass())) {
                run1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                run2 = m;
            } else if (types.length == 3 && types[0].isAssignableFrom(stringWriter.getClass())
                    && types[1].isAssignableFrom(args.getClass())
                    && types[2].isAssignableFrom(xcontext.getClass())) {
                run3 = m;
            }
        } else if (m.getName().equals("setContext")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 1 && types[0].isAssignableFrom(xcontext.getClass())) {
                setContext1 = m;
            } else if (types.length == 2 && types[0].isAssignableFrom(args.getClass())
                    && types[1].isAssignableFrom(xcontext.getClass())) {
                setContext2 = m;
            }
        } else if (m.getName().equals("getParser")) {
            Class<?>[] types = m.getParameterTypes();
            if (types.length == 0) {
                getParser = m;
            }
        }
        if (run2 != null && run3 != null && setContext1 != null && setContext2 != null && getParser != null)
            break;
    }

    if (run2 == null && run3 == null) {
        throw new MacroExecutionException(
                "Unable to find the appropriate run(Writer,XWikiContext) or run(Writer,Map,XWikiContext) method in the class.");
    }

    try {
        Object obj = klass.newInstance();
        if (setContext2 != null && (hasArgs || setContext1 == null)) {
            setContext2.invoke(obj, args, xcontext);
        } else if (setContext1 != null) {
            setContext1.invoke(obj, xcontext);
        }
        if (setContext2 != null || setContext1 != null) {
            if (getParser != null) {
                String parser = null;
                parser = (String) getParser.invoke(obj);
                if (parser != null) {
                    parameters.setParser(parser);
                }
            }
            run1.invoke(obj, stringWriter);
        } else {
            if (run3 != null && (hasArgs || run2 == null)) {
                run3.invoke(obj, stringWriter, args, xcontext);
            } else {
                run2.invoke(obj, stringWriter, xcontext);
            }
        }
    } catch (Exception e) {
        throw new MacroExecutionException(e.getMessage(), e);
    }

    return (stringWriter.toString());
}

From source file:edu.cornell.mannlib.vedit.util.OperationUtils.java

/**
 * Takes a bean and clones it using reflection. Any fields without standard
 * getter/setter methods will not be copied.
 *//*  ww  w.j ava  2  s .com*/
public static Object cloneBean(final Object bean, final Class<?> beanClass, final Class<?> iface) {
    if (bean == null) {
        throw new NullPointerException("bean may not be null.");
    }
    if (beanClass == null) {
        throw new NullPointerException("beanClass may not be null.");
    }
    if (iface == null) {
        throw new NullPointerException("iface may not be null.");
    }

    class CloneBeanException extends RuntimeException {
        public CloneBeanException(String message, Throwable cause) {
            super(message + " <" + cause.getClass().getSimpleName() + ">: bean=" + bean + ", beanClass="
                    + beanClass.getName() + ", iface=" + iface.getName(), cause);
        }
    }

    Object newBean;
    try {
        newBean = beanClass.getConstructor().newInstance();
    } catch (NoSuchMethodException e) {
        throw new CloneBeanException("bean has no 'nullary' constructor.", e);
    } catch (InstantiationException e) {
        throw new CloneBeanException("tried to create instance of an abstract class.", e);
    } catch (IllegalAccessException e) {
        throw new CloneBeanException("bean constructor is not accessible.", e);
    } catch (InvocationTargetException e) {
        throw new CloneBeanException("bean constructor threw an exception.", e);
    } catch (Exception e) {
        throw new CloneBeanException("failed to instantiate a new bean.", e);
    }

    for (Method beanMeth : iface.getMethods()) {
        String methName = beanMeth.getName();
        if (!methName.startsWith("get")) {
            continue;
        }
        if (beanMeth.getParameterTypes().length != 0) {
            continue;
        }
        String fieldName = methName.substring(3, methName.length());
        Class<?> returnType = beanMeth.getReturnType();

        Method setterMethod;
        try {
            setterMethod = iface.getMethod("set" + fieldName, returnType);
        } catch (NoSuchMethodException nsme) {
            continue;
        }

        Object fieldVal;
        try {
            fieldVal = beanMeth.invoke(bean, (Object[]) null);
        } catch (Exception e) {
            throw new CloneBeanException("failed to invoke " + beanMeth, e);
        }

        try {
            Object[] setArgs = new Object[1];
            setArgs[0] = fieldVal;
            setterMethod.invoke(newBean, setArgs);
        } catch (Exception e) {
            throw new CloneBeanException("failed to invoke " + setterMethod, e);
        }
    }
    return newBean;
}

From source file:io.apiman.manager.test.junit.ManagerRestTester.java

/**
 * Loads the test plans./*from  ww w.  j av  a 2 s. c o m*/
 * @param testClass
 * @throws InitializationError
 */
private void loadTestPlans(Class<?> testClass) throws InitializationError {
    try {
        ManagerRestTestPlan annotation = testClass.getAnnotation(ManagerRestTestPlan.class);
        if (annotation == null) {
            Method[] methods = testClass.getMethods();
            TreeSet<ManagerRestTestPlan> annotations = new TreeSet<>(new Comparator<ManagerRestTestPlan>() {
                @Override
                public int compare(ManagerRestTestPlan o1, ManagerRestTestPlan o2) {
                    Integer i1 = o1.order();
                    Integer i2 = o2.order();
                    return i1.compareTo(i2);
                }
            });
            for (Method method : methods) {
                annotation = method.getAnnotation(ManagerRestTestPlan.class);
                if (annotation != null) {
                    annotations.add(annotation);
                }
            }
            for (ManagerRestTestPlan anno : annotations) {
                TestPlanInfo planInfo = new TestPlanInfo();
                planInfo.planPath = anno.value();
                planInfo.name = new File(planInfo.planPath).getName();
                planInfo.endpoint = TestUtil.doPropertyReplacement(anno.endpoint());
                planInfo.plan = TestUtil.loadTestPlan(planInfo.planPath, testClass.getClassLoader());
                testPlans.add(planInfo);
            }
        } else {
            TestPlanInfo planInfo = new TestPlanInfo();
            planInfo.planPath = annotation.value();
            planInfo.name = new File(planInfo.planPath).getName();
            planInfo.plan = TestUtil.loadTestPlan(planInfo.planPath, testClass.getClassLoader());
            planInfo.endpoint = TestUtil.doPropertyReplacement(annotation.endpoint());
            testPlans.add(planInfo);
        }
    } catch (Throwable e) {
        throw new InitializationError(e);
    }

    if (testPlans.isEmpty()) {
        throw new InitializationError("No @ManagerRestTestPlan annotations found on test class: " + testClass);
    }
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

@SuppressWarnings("unchecked")
private void setupFor(Class<? extends Serializable> clz) {
    if (fieldNamesByClass.get(clz) == null) {
        List<String> fields = new ArrayList<>();
        List<Method> methods = new ArrayList<>();
        for (Method method : clz.getMethods()) {
            String columnName = null;
            if (method.isAnnotationPresent(Id.class) && method.isAnnotationPresent(GeneratedValue.class)
                    && method.getAnnotation(GeneratedValue.class).strategy() == GenerationType.IDENTITY) {
                // Ignore pk with identity strategy.
            } else if (method.isAnnotationPresent(Column.class)) {
                columnName = extractColumnName(method, clz);
            } else if (method.isAnnotationPresent(JoinColumn.class)
                    && method.getAnnotation(JoinColumn.class).insertable()) {
                columnName = method.getAnnotation(JoinColumn.class).name();
            } else if (method.isAnnotationPresent(EmbeddedId.class)) {
                // Handle Attribute override annotation ...
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride override : overrides.value()) {
                        fields.add(override.column().name());
                    }/* ww w .  j  a va2s . co m*/
                }
                methods.add(method);
            } else if (method.getReturnType().isAnnotationPresent(Embeddable.class)) {
                methods.add(method);
                // Embeddables can have column names remapped using attribute overrides.
                // We expect all attributes to be overridden. 
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride overrideAnnotation : overrides.value()) {
                        fields.add(overrideAnnotation.column().name());
                    }
                } else {
                    // Use the column names from the embeddable class. Assumption: @Column annotation exists.
                    for (Method embedded : method.getReturnType().getMethods()) {
                        if (embedded.isAnnotationPresent(Column.class)) {
                            fields.add(extractColumnName(embedded,
                                    (Class<? extends Serializable>) method.getReturnType()));
                        }
                    }
                }
            }
            if (columnName != null) {
                // Certain one-to-on join situations can lead to multiple columns with the same column-name.
                if (!fields.contains(columnName)) {
                    fields.add(columnName);
                    methods.add(method);
                }
            } // end if annotation present
        }
        extractorsByClass.put(clz, getExtractor(clz, methods));
        StringBuilder builder = new StringBuilder();
        for (String field : fields) {
            builder.append(",").append(field);
        }
        fieldNamesByClass.put(clz, builder.substring(1));
    }
}

From source file:com.heliumv.api.item.ItemApiV11.java

private SortierKriterium[] buildOrderBy(String orderBy, Class<?> theClass) {
    if (StringHelper.isEmpty(orderBy))
        return null;

    String[] orderbyTokens = orderBy.split(",");
    if (orderbyTokens.length == 0)
        return null;

    List<SortierKriterium> crits = new ArrayList<SortierKriterium>();
    Method[] methods = theClass.getMethods();

    for (String orderbyToken : orderbyTokens) {
        String[] token = orderbyToken.split(" ");
        boolean ascending = true;
        if (token.length > 1) {
            ascending = "asc".equals(token[1]);
        }/*from ww w . jav  a  2  s.c  o m*/

        for (Method theMethod : methods) {
            if (!theMethod.getName().startsWith("set"))
                continue;

            String variable = theMethod.getName().substring(3).toLowerCase();
            if (token[0].toLowerCase().equals(variable)) {

                HvFlrMapper flrMapper = theMethod.getAnnotation(HvFlrMapper.class);
                String sortName = flrMapper != null ? flrMapper.flrFieldName() : variable;
                if (sortName.length() == 0) {
                    throw new IllegalArgumentException("Unknown mapping for '" + token[0] + "'");
                }

                SortierKriterium crit = new SortierKriterium(sortName, true,
                        ascending ? SortierKriterium.SORT_ASC : SortierKriterium.SORT_DESC);
                crits.add(crit);
            }
        }
    }

    return crits.toArray(new SortierKriterium[0]);
}

From source file:com.gargoylesoftware.htmlunit.javascript.HtmlUnitScriptable.java

/**
 * {@inheritDoc}/*from   w w w . j av  a  2  s . co m*/
 * Same as base implementation, but includes all methods inherited from super classes as well.
 */
@Override
public void defineProperty(final String propertyName, final Class<?> clazz, int attributes) {
    final int length = propertyName.length();
    if (length == 0) {
        throw new IllegalArgumentException();
    }
    final char[] buf = new char[3 + length];
    propertyName.getChars(0, length, buf, 3);
    buf[3] = Character.toUpperCase(buf[3]);
    buf[0] = 'g';
    buf[1] = 'e';
    buf[2] = 't';
    final String getterName = new String(buf);
    buf[0] = 's';
    final String setterName = new String(buf);

    final Method[] methods = clazz.getMethods();
    final Method getter = findMethod(methods, getterName);
    final Method setter = findMethod(methods, setterName);
    if (setter == null) {
        attributes |= ScriptableObject.READONLY;
    }
    defineProperty(propertyName, null, getter, setter, attributes);
}

From source file:com.dianping.resource.io.util.ClassUtils.java

/**
 * Determine whether the given class has a public method with the given signature,
 * and return it if available (else return {@code null}).
 * <p>In case of any signature specified, only returns the method if there is a
 * unique candidate, i.e. a single public method with the specified name.
 * <p>Essentially translates {@code NoSuchMethodException} to {@code null}.
 * @param clazz the clazz to analyze/*from www.j  a  v  a2  s  . co  m*/
 * @param methodName the name of the method
 * @param paramTypes the parameter types of the method
 * (may be {@code null} to indicate any signature)
 * @return the method, or {@code null} if not found
 * @see Class#getMethod
 */
public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    if (paramTypes != null) {
        try {
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}

From source file:de.perdian.commons.i18n.polyglot.PolyglotImpl.java

private void appendInvocationInfos(Map<Method, PolyglotInvocationInfo> resultMap, Class<?> interfaceClass,
        PolyglotKeyGenerator keyGenerator) {
    Class<?>[] implementedInterfaces = interfaceClass.getInterfaces();
    if (implementedInterfaces != null) {
        for (Class<?> implementedInterface : implementedInterfaces) {
            this.appendInvocationInfos(resultMap, implementedInterface, keyGenerator);
        }/*from  w ww.ja  v  a2  s  .  co m*/
    }
    StringBuilder exceptionCollectionString = new StringBuilder();
    Method[] interfaceMethods = interfaceClass.getMethods();
    if (interfaceMethods != null) {
        for (Method interfaceMethod : interfaceMethods) {
            try {
                resultMap.put(interfaceMethod, this.createInvocationInfo(interfaceMethod, keyGenerator));
            } catch (Exception e) {
                exceptionCollectionString.append("\n- ").append(interfaceMethod.getName());
                exceptionCollectionString.append(": ").append(e.getMessage());
            }
        }
        if (exceptionCollectionString.length() > 0) {
            StringBuilder exceptionString = new StringBuilder();
            exceptionString.append("Analyzation of polyglot information for class '").append(interfaceClass)
                    .append("' ");
            exceptionString.append("failed:").append(exceptionCollectionString);
            throw new IllegalArgumentException(exceptionString.toString());
        }
    }
}

From source file:cn.teamlab.wg.framework.struts2.json.PackageBasedActionConfigBuilder.java

/**
 * Locates all of the {@link Json} annotations on methods within the Action
 * class and its parent classes./*from   w  w w  . ja  v  a2 s. com*/
 * 
 * @param actionClass
 *            The action class.
 * @return The list of annotations or an empty list if there are none.
 */
protected Map<String, List<Json>> getActionAnnotations(Class<?> actionClass) {
    Method[] methods = actionClass.getMethods();
    Map<String, List<Json>> map = new HashMap<String, List<Json>>();
    for (Method method : methods) {
        Json ann = method.getAnnotation(Json.class);
        if (ann != null) {
            map.put(method.getName(), Arrays.asList(ann));
        }
    }

    return map;
}

From source file:com.freetmp.common.util.ClassUtils.java

public static Method getMethodIfAvailable(Class<?> clazz, String methodName, Class<?>... paramTypes) {
    Assert.notNull(clazz, "Class must not be null");
    Assert.notNull(methodName, "Method name must not be null");
    if (paramTypes != null) {
        try {//from   www.  j a v  a 2  s.co m
            return clazz.getMethod(methodName, paramTypes);
        } catch (NoSuchMethodException ex) {
            return null;
        }
    } else {
        Set<Method> candidates = new HashSet<Method>(1);
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                candidates.add(method);
            }
        }
        if (candidates.size() == 1) {
            return candidates.iterator().next();
        }
        return null;
    }
}