Example usage for java.lang Class getMethod

List of usage examples for java.lang Class getMethod

Introduction

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

Prototype

@CallerSensitive
public Method getMethod(String name, Class<?>... parameterTypes)
        throws NoSuchMethodException, SecurityException 

Source Link

Document

Returns a Method object that reflects the specified public member method of the class or interface represented by this Class object.

Usage

From source file:com.aw.support.reflection.MethodInvoker.java

public static Object invoke(Object target, String methodName, Object[] parameters) throws Throwable {
    Object result = null;/*  ww w  . j  a  v a2  s  .  c o  m*/
    try {
        Class cls = target.getClass();
        Class[] paramTypes = new Class[parameters.length];
        for (int i = 0; i < paramTypes.length; i++) {
            paramTypes[i] = parameters[i].getClass();
        }
        Method method = cls.getMethod(methodName, paramTypes);
        method.setAccessible(true);
        result = method.invoke(target, parameters);
    } catch (Throwable e) {
        if (e.getCause() instanceof AWException) {
            throw ((AWException) e.getCause());
        }
        e.printStackTrace();
        throw e;
    }
    return result;
}

From source file:com.bellman.bible.service.common.CommonUtils.java

/**
 * By default popup menus do not show icons, but see the trick below
 * http://stackoverflow.com/questions/6805756/is-it-possible-to-display-icons-in-a-popupmenu
 *///from www  . j  a  va  2  s  .  c  om
public static void forcePopupMenuToShowIcons(PopupMenu popup) {
    try {
        Field[] fields = popup.getClass().getDeclaredFields();
        for (Field field : fields) {
            if ("mPopup".equals(field.getName())) {
                field.setAccessible(true);
                Object menuPopupHelper = field.get(popup);
                Class<?> classPopupHelper = Class.forName(menuPopupHelper.getClass().getName());
                Method setForceIcons = classPopupHelper.getMethod("setForceShowIcon", boolean.class);
                setForceIcons.invoke(menuPopupHelper, true);
                break;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

private static <A extends Annotation> A searchOnInterfaces(Method method, Class<A> annotationType,
        Class<?>[] ifcs) {/*w  w  w . j  ava 2s.co  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:Main.java

public static Object isEmpty(Object obj, Class clazz) {
    if (obj == null || clazz == null) {
        return obj;
    }/*from  w  w  w  .  j av  a2s  .c  om*/
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {
        try {
            String fieldName = field.getName();
            if (fieldName == null || fieldName.length() == 0)
                continue;
            String fieldMethodName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
            String getfieldName = "get" + fieldMethodName;
            Method getMethod = clazz.getMethod(getfieldName, null);
            if (getMethod == null)
                continue;
            Object value = getMethod.invoke(obj, null);
            Class type = field.getType();
            if (type == String.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().trim().length() == 0) {
                    value = "";
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, String.class);
                    if (setMethod == null)
                        continue;
                    setMethod.invoke(obj, value);
                }
            } else if (type == Integer.class || type == int.class || type == Float.class || type == float.class
                    || type == Double.class || type == double.class) {
                if (value == null || "null".equals(value.toString()) || value.toString().length() == 0) {
                    String setfieldName = "set" + fieldMethodName;
                    Method setMethod = clazz.getMethod(setfieldName, type);
                    setMethod.invoke(obj, 0);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            continue;
        }
    }
    return obj;
}

From source file:nz.co.senanque.validationengine.ConvertUtils.java

public static Object convertToObject(Class<?> clazz, Object obj, MessageSourceAccessor messageSourceAccessor) {
    try {/*ww  w.ja v  a 2s  .c  om*/
        return convertTo(clazz, obj);
    } catch (RuntimeException e) {
        if (clazz.isEnum()) {
            Object o;
            try {
                //                    Method[] methods = clazz.getMethods();
                Method fromValueMethod = clazz.getMethod("fromValue", String.class);
                final String oStr = String.valueOf(obj);
                o = fromValueMethod.invoke(null, oStr);
                return o;
            } catch (Exception e1) {
            }
        }
        if (messageSourceAccessor != null) {
            String message = messageSourceAccessor.getMessage(s_message,
                    new Object[] { obj.getClass().getSimpleName(), clazz.getSimpleName() });
            throw new ValidationException(message);
        } else {
            throw new RuntimeException(
                    "Cannot convert from " + obj.getClass().getName() + " to " + clazz.getName());
        }
    }
}

From source file:com.microsoft.tfs.core.util.UserNameUtil.java

private static NTUserInfo lookUpNTUserInfo() {
    try {/* w w  w  .  j a  v a  2  s .  co  m*/
        final Class c = Class.forName("com.sun.security.auth.module.NTSystem"); //$NON-NLS-1$
        final Object instance = c.newInstance();

        final String userName = (String) c.getMethod("getName", (Class[]) null).invoke(instance, //$NON-NLS-1$
                (Object[]) null);
        final String domain = (String) c.getMethod("getDomain", (Class[]) null).invoke(instance, //$NON-NLS-1$
                (Object[]) null);
        final String domainSID = (String) c.getMethod("getDomainSID", (Class[]) null).invoke(instance, //$NON-NLS-1$
                (Object[]) null);
        final String userSID = (String) c.getMethod("getUserSID", (Class[]) null).invoke(instance, //$NON-NLS-1$
                (Object[]) null);
        final String primaryGroupID = (String) c.getMethod("getPrimaryGroupID", (Class[]) null).invoke( //$NON-NLS-1$
                instance, (Object[]) null);
        final String[] groupIDs = (String[]) c.getMethod("getGroupIDs", (Class[]) null).invoke(instance, //$NON-NLS-1$
                (Object[]) null);
        final long impersonationToken = ((Long) c.getMethod("getImpersonationToken", (Class[]) null).invoke( //$NON-NLS-1$
                instance, (Object[]) null)).longValue();

        return new NTUserInfo(userName, domain, domainSID, userSID, primaryGroupID, groupIDs,
                impersonationToken);
    } catch (final Throwable t) {
        if (log.isDebugEnabled()) {
            log.debug("Unable to get NT user info", t); //$NON-NLS-1$
        }

        return null;
    }
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static void executeManagixCommand(String command) throws ClassNotFoundException, NoSuchMethodException,
        SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    if (managixExecuteMethod == null) {
        Class<?> clazz = Class.forName("edu.uci.ics.asterix.installer.test.AsterixInstallerIntegrationUtil");
        managixExecuteMethod = clazz.getMethod("executeCommand", String.class);
    }/*ww w  .j  a  v a 2s.c  om*/
    managixExecuteMethod.invoke(null, command);
}

From source file:com.dubsar_dictionary.Dubsar.FAQActivity.java

/**
 * Set Proxy for Android 3.2 and below./*from w  w w .jav a2  s  .com*/
 */
@SuppressWarnings("all")
private static boolean setProxyUpToHC(WebView webview, String host, int port) {
    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API.");

    HttpHost proxyServer = new HttpHost(host, port);
    // Getting network
    Class networkClass = null;
    Object network = null;
    try {
        networkClass = Class.forName("android.webkit.Network");
        if (networkClass == null) {
            Log.e(LOG_TAG, "failed to get class for android.webkit.Network");
            return false;
        }
        Method getInstanceMethod = networkClass.getMethod("getInstance", Context.class);
        if (getInstanceMethod == null) {
            Log.e(LOG_TAG, "failed to get getInstance method");
        }
        network = getInstanceMethod.invoke(networkClass, new Object[] { webview.getContext() });
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting network: " + ex);
        return false;
    }
    if (network == null) {
        Log.e(LOG_TAG, "error getting network: network is null");
        return false;
    }
    Object requestQueue = null;
    try {
        Field requestQueueField = networkClass.getDeclaredField("mRequestQueue");
        requestQueue = getFieldValueSafely(requestQueueField, network);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting field value");
        return false;
    }
    if (requestQueue == null) {
        Log.e(LOG_TAG, "Request queue is null");
        return false;
    }
    Field proxyHostField = null;
    try {
        Class requestQueueClass = Class.forName("android.net.http.RequestQueue");
        proxyHostField = requestQueueClass.getDeclaredField("mProxyHost");
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error getting proxy host field");
        return false;
    }

    boolean temp = proxyHostField.isAccessible();
    try {
        proxyHostField.setAccessible(true);
        proxyHostField.set(requestQueue, proxyServer);
    } catch (Exception ex) {
        Log.e(LOG_TAG, "error setting proxy host");
    } finally {
        proxyHostField.setAccessible(temp);
    }

    Log.d(LOG_TAG, "Setting proxy with <= 3.2 API successful!");
    return true;
}

From source file:com.gigaspaces.internal.utils.ClassLoaderCleaner.java

/**
 * Clear references./*from   w  w w  .  j  a v a  2s  .  c o m*/
 */
public static void clearReferences(ClassLoader classLoader) {
    ClassLoaderCache.getCache().removeClassLoader(classLoader);

    if (NonActivatableServiceDescriptor.getGlobalPolicy() != null) {
        NonActivatableServiceDescriptor.getGlobalPolicy().setPolicy(classLoader, null);
    }

    // De-register any remaining JDBC drivers
    clearReferencesJdbc(classLoader);

    // Stop any threads the web application started
    clearReferencesThreads(classLoader);

    // Clear any ThreadLocals loaded by this class loader
    clearReferencesThreadLocals(classLoader);

    // Clear RMI Targets loaded by this class loader
    clearReferencesRmiTargets(classLoader);

    clearRmiLoaderHandler(classLoader);

    // Clear the classloader reference in common-logging
    try {
        Class clazz = classLoader.loadClass("org.apache.commons.logging.LogFactory");
        clazz.getMethod("release", ClassLoader.class).invoke(null, classLoader);
    } catch (Throwable t) {
        // ignore
    }
    try {
        Class clazz = classLoader.loadClass("org.apache.juli.logging.LogFactory");
        clazz.getMethod("release", ClassLoader.class).invoke(null, classLoader);
    } catch (Throwable t) {
        // ignore
    }

    // Clear the resource bundle cache
    // This shouldn't be necessary, the cache uses weak references but
    // it has caused leaks. Oddly, using the leak detection code in
    // standard host allows the class loader to be GC'd. This has been seen
    // on Sun but not IBM JREs. Maybe a bug in Sun's GC impl?
    clearReferencesResourceBundles(classLoader);

    // Clear the classloader reference in the VM's bean introspector
    java.beans.Introspector.flushCaches();

}

From source file:com.aurel.track.persist.ReflectionHelper.java

/**
 * This method replaces all occurrences of 
 * oldOID with newOID going through all related
 * tables in the database.//from w  w w.  j a v  a  2  s . com
 * @param oldOID object identifier to be replaced
 * @param newOID object identifier of replacement
 */
public static void replace(Class[] peerClasses, String[] fields, Integer oldOID, Integer newOID) {
    Criteria selectCriteria = new Criteria();
    Criteria updateCriteria = new Criteria();
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        selectCriteria.clear();
        updateCriteria.clear();
        selectCriteria.add(field, oldOID, Criteria.EQUAL);
        updateCriteria.add(field, newOID);
        try {
            Class partypes[] = new Class[2];
            partypes[0] = Criteria.class;
            partypes[1] = Criteria.class;
            Method meth = peerClass.getMethod("doUpdate", partypes);

            Object arglist[] = new Object[2];
            arglist[0] = selectCriteria;
            arglist[1] = updateCriteria;
            meth.invoke(peerClass, arglist);
        } catch (Exception e) {
            LOGGER.error("Exception when trying to replace " + "oldOID " + oldOID + " with " + "newOID "
                    + newOID + " for class " + peerClass.toString() + " and field " + field + ": "
                    + e.getMessage(), e);
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
}