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:com.ksmpartners.ernie.util.TestUtil.java

/**
 * Invoke the specified method and translate failures into assertion
 * failures./*from  w  ww.  j a v  a2 s  .  c o  m*/
 * <p>
 * @param target the target object
 * @param method the Method to invoke
 * @param value the value to pass in
 * @param qName a qualified property name for reporting failures
 * @return the object value returned if any
 */
private static Object invokeMethod(Object target, Method method, Object[] value, String qName) {
    try {
        Object result = method.invoke(target, value);
        return result;
    } catch (Exception e) {
        Assert.fail("Failed invoking method " + method.getName() + " for property " + qName + ": "
                + e.getMessage());
        return null;
    }
}

From source file:com.lemi.mario.download.http.AndroidHttpClient.java

/**
 * Create a new HttpClient with reasonable defaults (which you can update).
 *
 * @param userAgent to report in your HTTP requests
 * @param context to use for caching SSL sessions (may be null for no caching)
 * @return AndroidHttpClient for you to use for all your requests.
 *//*from  w w  w. j  av  a2s .  co  m*/
public static AndroidHttpClient newInstance(String userAgent, Context context) {
    HttpParams params = new BasicHttpParams();

    // Turn off stale checking. Our connections break all the time anyway,
    // and it's not worth it to pay the penalty of checking every time.
    HttpConnectionParams.setStaleCheckingEnabled(params, false);

    HttpConnectionParams.setConnectionTimeout(params, CONNECT_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, SOCKET_TIMEOUT);
    HttpConnectionParams.setSocketBufferSize(params, 8192);

    // Don't handle redirects -- return them to the caller. Our code
    // often wants to re-POST after a redirect, which we must do ourselves.
    HttpClientParams.setRedirecting(params, false);

    // Use a session cache for SSL sockets
    // SSLSessionCache sessionCache = context == null ? null : new SSLSessionCache(context);

    // Set the specified user agent and register standard protocols.
    HttpProtocolParams.setUserAgent(params, userAgent);
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));

    // use reflection to invoke methods.
    SocketFactory factory = null;
    try {
        Method[] methods = SSLCertificateSocketFactory.class.getMethods();
        for (Method method : methods) {
            if (method.getName().equals("getHttpSocketFactory")) {
                Object retValue = method.invoke(SSLCertificateSocketFactory.class,
                        new Object[] { CONNECT_TIMEOUT, null });
                if (retValue != null && retValue instanceof SocketFactory) {
                    factory = (SocketFactory) retValue;
                }
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (factory != null) {
        schemeRegistry.register(new Scheme("https", factory
        /*
         * SSLCertificateSocketFactory.getHttpSocketFactory(
         * CONNECTION_TIMEOUT, nullsessionCache)
         */, 443));
    }

    ClientConnectionManager manager = new ThreadSafeClientConnManager(params, schemeRegistry);

    // We use a factory method to modify superclass initialization
    // parameters without the funny call-a-static-method dance.
    return new AndroidHttpClient(manager, params);
}

From source file:net.kamhon.ieagle.util.VoUtil.java

/**
 * To trim object String field//from   w  ww .  j a v a2 s  . com
 * 
 * @param all
 *            default is false. true means toTrim all String field, false toTrim the fields have
 *            net.kamhon.ieagle.vo.core.annotation.ToTrim.
 * 
 * @param objects
 */
public static void toTrimProperties(boolean all, Object... objects) {
    for (Object object : objects) {
        if (object == null) {
            continue;
        }

        // getter for String field only
        Map<String, Method> getterMap = new HashMap<String, Method>();
        // setter for String field only
        Map<String, Method> setterMap = new HashMap<String, Method>();

        Class<?> clazz = object.getClass();

        Method[] methods = clazz.getMethods();

        for (Method method : methods) {
            if (method.getName().startsWith("get") && method.getParameterTypes().length == 0
                    && method.getReturnType().equals(String.class)) {

                // if method name is getXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                getterMap.put(fieldName, method);
            } else if (method.getName().startsWith("set") && method.getParameterTypes().length == 1
                    && method.getParameterTypes()[0] == String.class
                    && method.getReturnType().equals(void.class)) {
                // log.debug("setter = " + method.getName());

                // if method name is setXxx
                String fieldName = method.getName().substring(3);
                fieldName = fieldName.substring(0, 1).toLowerCase() + fieldName.substring(1);

                setterMap.put(fieldName, method);
            }
        }

        // if the key exists in both getter & setter
        for (String key : getterMap.keySet()) {
            if (setterMap.containsKey(key)) {
                try {
                    Method getterMethod = getterMap.get(key);
                    Method setterMethod = setterMap.get(key);

                    // if not all, check on Field
                    if (!all) {
                        Field field = null;

                        Class<?> tmpClazz = clazz;
                        // looping up to superclass to get decleared field
                        do {
                            try {
                                field = tmpClazz.getDeclaredField(key);
                            } catch (Exception ex) {
                                // do nothing
                            }

                            if (field != null) {
                                break;
                            }

                            tmpClazz = tmpClazz.getSuperclass();
                        } while (tmpClazz != null);

                        ToTrim toTrim = field.getAnnotation(ToTrim.class);
                        if (toTrim == null || toTrim.trim() == false) {
                            continue;
                        }
                    }

                    String value = (String) getterMethod.invoke(object, new Object[] {});

                    if (StringUtils.isNotBlank(value))
                        setterMethod.invoke(object, value.trim());

                } catch (Exception ex) {
                    // log.error("Getter Setter for " + key + " has error ", ex);
                }
            }
        }
    }
}

From source file:com.acuityph.commons.util.ClassUtils.java

/**
 * Checks if the given method matches the JavaBean property setter signature.
 *
 * @param method//from  w  w w .j  a  va2  s  .  co  m
 *        the method to check
 * @return {@code true}, if the method matchers the JavaBean property setter signature
 */
public static boolean isPropertySetter(final Method method) {
    Assert.notNull(method, "method is null!");
    final int mod = method.getModifiers();
    final boolean expectsOneParameter = method.getParameterTypes().length == 1;
    final boolean returnsVoid = void.class.equals(method.getReturnType());
    return !isPrivate(mod) && !isStatic(mod) && expectsOneParameter && returnsVoid
            && isPropertySetterName(method.getName());
}

From source file:com.palantir.ptoss.cinch.core.BindingContext.java

private static Map<String, ObjectFieldMethod> indexMethods(List<ObjectFieldMethod> methods)
        throws IllegalArgumentException {
    Map<String, ObjectFieldMethod> map = Maps.newHashMap();
    Set<String> ambiguousNames = Sets.newHashSet();
    for (ObjectFieldMethod ofm : methods) {
        Method method = ofm.getMethod();
        String blindKey = method.getName();
        if (!ambiguousNames.contains(blindKey)) {
            if (map.containsKey(blindKey)) {
                map.remove(blindKey);/* w w w  .ja  v a2  s  .co  m*/
                ambiguousNames.add(blindKey);
            } else {
                map.put(blindKey, ofm);
            }
        }
        String fieldName = ofm.getField() == null ? "this" : ofm.getField().getName();
        String qualifiedKey = fieldName + "." + blindKey;
        map.put(qualifiedKey, ofm);
    }
    return map;
}

From source file:com.mine.core.util.ReflectUtils.java

/**
 * ????/*from ww w .  ja va 2 s.co  m*/
 *
 * @param clazz
 * @param methodName
 * @return
 */
public static Class<?> getMethodReturnTypeByName(Class<?> clazz, String methodName) {
    Validate.notNull(clazz, "calzz can't be null");
    Validate.notBlank(methodName);
    Method[] methods = clazz.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName)) {
            return method.getReturnType();
        }
    }
    return null;
}

From source file:com.acuityph.commons.util.ClassUtils.java

/**
 * Checks if is property getter./*w ww . jav a2 s . c  o m*/
 *
 * @param method
 *        the method
 * @return true, if is property getter
 */
public static boolean isPropertyGetter(final Method method) {
    Assert.notNull(method, "method is null!");
    final int mod = method.getModifiers();
    final boolean expectsNoParameters = method.getParameterTypes().length == 0;
    final boolean returnsSomething = !void.class.equals(method.getReturnType());
    return !isPrivate(mod) && !isStatic(mod) && expectsNoParameters && returnsSomething
            && isPropertyGetterName(method.getName());
}

From source file:com.eucalyptus.upgrade.TestHarness.java

@SuppressWarnings({ "static-access" })
private static void printHelp(Options opts) {
    try {/*from  ww w  .  j  a  v  a2s.co  m*/
        PrintWriter out = new PrintWriter(System.out);
        HelpFormatter help = new HelpFormatter();
        help.setArgName("TESTS");
        help.printHelp(out, LINE_BYTES, "java -jar test.jar", "Options controlling the test harness.", opts, 2,
                4, "", true);
        Multimap<Class, Method> testMethods = getTestMethods();
        help = new HelpFormatter();
        help.setLongOptPrefix("");
        help.setOptPrefix("");
        help.setSyntaxPrefix("");
        help.setLeftPadding(0);
        Options testOptions = new Options();
        for (Class c : testMethods.keySet()) {
            testOptions.addOption(
                    OptionBuilder.withDescription(getDescription(c)).withLongOpt(c.getSimpleName()).create());
            for (Method m : testMethods.get(c)) {
                testOptions.addOption(OptionBuilder.withDescription(getDescription(m))
                        .withLongOpt(c.getSimpleName() + "." + m.getName()).create());
            }
        }
        help.printHelp(out, LINE_BYTES, " ", "Tests:", testOptions, 0, 2, "", false);
        out.flush();
    } catch (Exception e) {
        System.out.println(e);
        System.exit(1);
    }
}

From source file:org.synyx.hades.util.ClassUtils.java

/**
 * Returns the given base class' method if the given method (declared in the
 * interface) was also declared at the base class. Returns the given method
 * if the given base class does not declare the method given. Takes generics
 * into account./*from   ww  w  .j  a  va 2  s .  c o  m*/
 * 
 * @param method
 * @param baseClass
 * @param daoInterface
 * @return
 */
public static Method getBaseClassMethodFor(Method method, Class<?> baseClass, Class<?> daoInterface) {

    for (Method daoClassMethod : baseClass.getMethods()) {

        // Wrong name
        if (!method.getName().equals(daoClassMethod.getName())) {
            continue;
        }

        // Wrong number of arguments
        if (!(method.getParameterTypes().length == daoClassMethod.getParameterTypes().length)) {
            continue;
        }

        // Check whether all parameters match
        if (!parametersMatch(method, daoClassMethod, daoInterface)) {
            continue;
        }

        return daoClassMethod;
    }

    return method;
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 *
 *
 * @param entityClazz/*  www  . j  a  v  a 2s.c o  m*/
 * @param propertyName
 * @return
 */
public static <T> Method findSetterMethod(Class<T> entityClazz, String propertyName) {
    for (Method methodCandidate : entityClazz.getDeclaredMethods()) {
        String methodCandidateName = methodCandidate.getName();
        if (methodCandidateName.startsWith("set") && methodCandidateName.endsWith(propertyName)) {
            return methodCandidate;
        }
    }
    return null;
}