Example usage for java.lang.reflect Method getName

List of usage examples for java.lang.reflect Method getName

Introduction

In this page you can find the example usage for java.lang.reflect Method getName.

Prototype

@Override
public String getName() 

Source Link

Document

Returns the name of the method represented by this Method object, as a String .

Usage

From source file:org.callimachusproject.webdriver.helpers.BrowserFunctionalTestCase.java

private static void addTests(Class<? extends BrowserFunctionalTestCase> testcase, TestSuite suite,
        Method method) throws InstantiationException, IllegalAccessException {
    for (String browser : getInstalledWebDrivers().keySet()) {
        BrowserFunctionalTestCase test = testcase.newInstance();
        test.setName(method.getName() + DELIM + browser);
        suite.addTest(test);// www.j a  v a  2s . c o  m
    }
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}/*from   w  ww . j ava2s .c  o  m*/
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:net.roboconf.target.docker.internal.DockerUtils.java

/**
 * Finds the options and tries to configure them on the creation command.
 * @param options the options (key = name, value = option value)
 * @param cmd a non-null command to create a container
 * @throws TargetException/*  w  ww.j  a  v a  2  s.  c o  m*/
 */
public static void configureOptions(Map<String, String> options, CreateContainerCmd cmd)
        throws TargetException {

    Logger logger = Logger.getLogger(DockerUtils.class.getName());

    // Basically, we had two choices:
    // 1. Map our properties to the Java REST API.
    // 2. By-pass it and send our custom JSon object.
    //
    // The second option is much more complicated.
    // So, we use Java reflection and some hacks to match Docker properties
    // with the setter methods available in the API. The API remains in charge
    // of generating the right JSon objects.
    Map<String, List<String>> hackedSetterNames = new HashMap<>();

    // Remains from Docker-Java 2.x (the mechanism still works)
    //
    //      List<String> list = new ArrayList<> ();
    //      list.add( "withMemoryLimit" );
    //      hackedSetterNames.put( "withMemory", list );

    // List known types
    List<Class<?>> types = new ArrayList<>();
    types.add(String.class);
    types.add(String[].class);
    types.add(long.class);
    types.add(Long.class);
    types.add(int.class);
    types.add(Integer.class);
    types.add(boolean.class);
    types.add(Boolean.class);
    types.add(Capability[].class);

    // Deal with the options
    for (Map.Entry<String, String> entry : options.entrySet()) {
        String optionValue = entry.getValue();

        // Now, guess what option to set
        String methodName = entry.getKey().replace("-", " ").trim();
        methodName = WordUtils.capitalize(methodName);
        methodName = methodName.replace(" ", "");
        methodName = "with" + methodName;

        Method _m = null;
        for (Method m : cmd.getClass().getMethods()) {

            boolean sameMethod = methodName.equalsIgnoreCase(m.getName());
            boolean methodWithAlias = hackedSetterNames.containsKey(methodName)
                    && hackedSetterNames.get(methodName).contains(m.getName());

            if (sameMethod || methodWithAlias) {

                // Only one parameter?
                if (m.getParameterTypes().length != 1) {
                    logger.warning("A method was found for " + entry.getKey()
                            + " but it does not have the right number of parameters.");
                    continue;
                }

                // The right type?
                if (!types.contains(m.getParameterTypes()[0])) {

                    // Since Docker-java 3.x, there are two methods to set cap-add and cap-drop.
                    // One takes an array as parameter, the other takes a list.
                    logger.warning("A method was found for " + entry.getKey()
                            + " but it does not have the right parameter type. "
                            + "Skipping it. You may want to add a feature request.");

                    continue;
                }

                // That's probably the right one.
                _m = m;
                break;
            }
        }

        // Handle errors
        if (_m == null)
            throw new TargetException(
                    "Nothing matched the " + entry.getKey() + " option in the REST API. Please, report it.");

        // Try to set the option in the REST client
        try {
            Object o = prepareParameter(optionValue, _m.getParameterTypes()[0]);
            _m.invoke(cmd, o);

        } catch (ReflectiveOperationException | IllegalArgumentException e) {
            throw new TargetException("Option " + entry.getKey() + " could not be set.");
        }
    }
}

From source file:org.jdbcluster.JDBClusterUtil.java

/**
 * Tries to determine the best fitting method for a set of parameter types.
 * Uses getMethod() first, if there is no direct match every parameter is
 * checked if there is a method with a superclass or superinterface match.
 * etc. For this best fitting method a scoring is used. It counts for every
 * parameter the "distance" from the class to the requested superclass or
 * superinterface. These "distances" are cummulated to one value. The method
 * with the lowest scoring value is returned.
 * /*from   w  ww  .ja  v a  2 s.  c  o  m*/
 * @see #getMethod(Class, String, Class[])
 * @param clazz
 *            Class of Object
 * @param methodName
 *            name of the method to find
 * @param parameterTypes
 *            parameter types of method
 * @return Method to find
 */
static public Method getMethodBestParameterFit(Class clazz, String methodName, Class... parameterTypes) {

    /*
     * first try the normal way (exact match)
     */
    try {
        return JDBClusterUtil.getMethod(clazz, methodName, parameterTypes);
    } catch (ConfigurationException e) {
        if (!(e.getCause() instanceof NoSuchMethodException))
            throw e;
    }

    /*
     * get all methods and select only equal name and parameter length in
     * mList
     */
    Method[] mAll = clazz.getMethods();
    List<Method> mList = new ArrayList<Method>();

    for (Method m : mAll) {
        if (m.getParameterTypes().length == parameterTypes.length && m.getName().equals(methodName))
            mList.add(m);
    }

    if (mList.size() > 1)
        logger.warn("possible ambiguity. Found more than one method with name [" + methodName + "]. "
                + "trying best fit method");

    /*
     * check if parameter superclasses do fit for all above selected methods
     */
    HashMap<Method, Integer> methodScore = new HashMap<Method, Integer>();
    for (Method m : mList) {
        Class<?>[] mParameterTypes = m.getParameterTypes();

        for (int i = 0; i < parameterTypes.length; i++) {
            int count = countSuper(mParameterTypes[i], parameterTypes[i]);
            Integer oldInt = methodScore.get(m);
            if (oldInt == null)
                oldInt = 0;
            methodScore.put(m, oldInt + count);
            if (count < 0) {
                methodScore.put(m, -1);
                break; // if there is no match this method is not fitting
            }
        }
    }

    /*
     * evaluate scoring
     */
    Method mResult = null;
    int resultScore = Integer.MAX_VALUE;
    for (Method m : mList) {
        int score = methodScore.get(m);
        if (score != -1) {
            if (score < resultScore) {
                resultScore = score;
                mResult = m;
            }
        }
    }

    if (mResult == null)
        throw new ConfigurationException(
                "cant get MethodBestParameterFit for method [" + methodName + "] with the specified name");

    return mResult;
}

From source file:io.stallion.reflection.PropertyUtils.java

/**
 * Build a map of direct javabeans properties of the target object. Only read/write properties (ie: those who have
 * both a getter and a setter) are returned.
 * @param target the target object from which to get properties names.
 * @return a Map of String with properties names as key and their values
 * @throws PropertyException if an error happened while trying to get a property.
 *//*from w  ww.j  a  v  a 2  s  .  c  o  m*/
public static Map<String, Object> getProperties(Object target,
        Class<? extends Annotation>... excludeAnnotations) throws PropertyException {
    Map<String, Object> properties = new HashMap<String, Object>();
    Class clazz = target.getClass();
    Method[] methods = clazz.getMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        String name = method.getName();
        Boolean hasExcludeAnno = false;
        if (excludeAnnotations.length > 0) {
            for (Class<? extends Annotation> anno : excludeAnnotations) {
                if (method.isAnnotationPresent(anno)) {
                    hasExcludeAnno = true;
                }
            }
        }
        if (hasExcludeAnno) {
            continue;
        }
        if (method.getModifiers() == Modifier.PUBLIC && method.getParameterTypes().length == 0
                && (name.startsWith("get") || name.startsWith("is"))
                && containsSetterForGetter(clazz, method)) {
            String propertyName;
            if (name.startsWith("get"))
                propertyName = Character.toLowerCase(name.charAt(3)) + name.substring(4);
            else if (name.startsWith("is"))
                propertyName = Character.toLowerCase(name.charAt(2)) + name.substring(3);
            else
                throw new PropertyException(
                        "method '" + name + "' is not a getter, thereof no setter can be found");

            try {
                Object propertyValue = method.invoke(target, (Object[]) null); // casting to (Object[]) b/c of javac 1.5 warning
                if (propertyValue != null && propertyValue instanceof Properties) {
                    Map propertiesContent = getNestedProperties(propertyName, (Properties) propertyValue);
                    properties.putAll(propertiesContent);
                } else {
                    properties.put(propertyName, propertyValue);
                }
            } catch (IllegalAccessException ex) {
                throw new PropertyException("cannot set property '" + propertyName + "' - '" + name
                        + "' is null and cannot be auto-filled", ex);
            } catch (InvocationTargetException ex) {
                throw new PropertyException("cannot set property '" + propertyName + "' - '" + name
                        + "' is null and cannot be auto-filled", ex);
            }

        } // if
    } // for

    return properties;
}

From source file:com.facebook.GraphObjectWrapper.java

private static <T extends GraphObject> void verifyCanProxyClass(Class<T> graphObjectClass) {
    if (hasClassBeenVerified(graphObjectClass)) {
        return;/*from ww w .j av a2 s  .  com*/
    }

    if (!graphObjectClass.isInterface()) {
        throw new FacebookGraphObjectException(
                "GraphObjectWrapper can only wrap interfaces, not class: " + graphObjectClass.getName());
    }

    Method[] methods = graphObjectClass.getMethods();
    for (Method method : methods) {
        String methodName = method.getName();
        int parameterCount = method.getParameterTypes().length;
        Class<?> returnType = method.getReturnType();
        boolean hasPropertyNameOverride = method.isAnnotationPresent(PropertyName.class);

        if (method.getDeclaringClass().isAssignableFrom(GraphObject.class)) {
            // Don't worry about any methods from GraphObject or one of its base classes.
            continue;
        } else if (parameterCount == 1 && returnType == Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("set") && methodName.length() > 3) {
                // Looks like a valid setter
                continue;
            }
        } else if (parameterCount == 0 && returnType != Void.TYPE) {
            if (hasPropertyNameOverride) {
                // If a property override is present, it MUST be valid. We don't fallback
                // to using the method name
                if (!Utility.isNullOrEmpty(method.getAnnotation(PropertyName.class).value())) {
                    continue;
                }
            } else if (methodName.startsWith("get") && methodName.length() > 3) {
                // Looks like a valid getter
                continue;
            }
        }

        throw new FacebookGraphObjectException("GraphObjectWrapper can't proxy method: " + method.toString());
    }

    recordClassHasBeenVerified(graphObjectClass);
}

From source file:com.github.valdr.thirdparty.spring.AnnotationUtils.java

private static <A extends Annotation> A searchOnInterfaces(Method method, Class<A> annotationType,
        Class<?>[] ifcs) {/*from www.java  2  s  . c  o m*/
    A annotation = null;
    for (Class<?> iface : ifcs) {
        if (isInterfaceWithAnnotatedMethods(iface)) {
            try {
                Method equivalentMethod = iface.getMethod(method.getName(), method.getParameterTypes());
                annotation = getAnnotation(equivalentMethod, annotationType);
            } catch (NoSuchMethodException ex) {
                // Skip this interface - it doesn't have the method...
            }
            if (annotation != null) {
                break;
            }
        }
    }
    return annotation;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Determine whether the given method is a "hashCode" method.
 * @see java.lang.Object#hashCode()//from  w  ww  . j  a  va 2 s  . c om
 */
public static boolean isHashCodeMethod(Method method) {
    return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0);
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Determine whether the given method is a "toString" method.
 * @see java.lang.Object#toString()// w  w w  .j  a v a2s . c  o m
 */
public static boolean isToStringMethod(Method method) {
    return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Determine whether the given method is an "equals" method.
 * @see java.lang.Object#equals(Object)/*from   w w  w.  j av a2s.  com*/
 */
public static boolean isEqualsMethod(Method method) {
    if (method == null || !method.getName().equals("equals")) {
        return false;
    }
    Class<?>[] paramTypes = method.getParameterTypes();
    return (paramTypes.length == 1 && paramTypes[0] == Object.class);
}