Example usage for java.lang Class getDeclaredMethod

List of usage examples for java.lang Class getDeclaredMethod

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:net.sourceforge.atunes.utils.ReflectionUtils.java

/**
 * Returns method object or null if any error happens
 * //from w  w  w.j  ava  2  s  .com
 * @param clazz
 * @param methodName
 * @param arguments
 * @return
 */
public static Method getMethod(final Class<?> clazz, final String methodName, final Class<?>... arguments) {
    try {
        return clazz.getDeclaredMethod(methodName, arguments);
    } catch (IllegalArgumentException e) {
        Logger.error(e);
    } catch (SecurityException e) {
        Logger.error(e);
    } catch (NoSuchMethodException e) {
        Logger.error(e);
    }
    return null;
}

From source file:io.dyn.core.handler.Handlers.java

public static <A extends Annotation> A find(Class<A> anno, Method method) {
    if (null == method) {
        return null;
    }//from   w ww.  j  a  va  2 s  . c  o  m

    A on = AnnotationUtils.findAnnotation(method, anno);
    if (null != on) {
        return on;
    }

    Class<?>[] implClasses = method.getDeclaringClass().getInterfaces();
    for (Class<?> cl : implClasses) {
        try {
            Method m = cl.getDeclaredMethod(method.getName(), method.getParameterTypes());
            if (null != m) {
                on = find(anno, m);
                if (null != on) {
                    return on;
                }
            }
        } catch (NoSuchMethodException e) {
        }
    }

    return null;
}

From source file:com.jkoolcloud.tnt4j.streams.utils.LoggerUtils.java

private static Object invoke(Object obj, String className, String methodName, Class<?>[] paramTypes,
        Object... params) throws Exception {
    Class<?> cls = obj == null ? Class.forName(className) : obj.getClass();
    Method m = cls.getDeclaredMethod(methodName, paramTypes);
    return m.invoke(obj, params);
}

From source file:nl.b3p.catalog.arcgis.ArcObjectsLinker.java

public static void link(String arcObjectsHome) throws Exception {

    if (arcObjectsHome == null) {
        for (String s : homeEnvVars) {
            arcObjectsHome = System.getenv(s);
            if (arcObjectsHome != null) {
                log.info("Using environment variable " + s + " to find ArcObjects");
                break;
            }/*from w  w w  .j a  v  a 2  s.c o  m*/
        }
    }
    if (arcObjectsHome == null) {
        throw new Exception("Could not find ArcObjects home in environment variables " + homeEnvVars + ". "
                + (System.getProperty("os.name").toLowerCase().indexOf("win") > -1
                        ? "ArcGIS Engine Runtime or ArcGIS Desktop must be installed"
                        : "ArcGIS Engine Runtime must be installed"));
    }

    // The directory can be set to a JAR itself, the directory arcobjects.jar
    // is in, or (as in the environment variables) the path with "java/lib" 
    // subdirectories with arcobjects.jar in it (some reports ArcGIS Server
    // 10.1 not having these java/lib subdirs).

    File jarFile = null;

    if (arcObjectsHome.endsWith(".jar")) {
        jarFile = new File(arcObjectsHome);
        if (jarFile.exists()) {
            log.info(String.format("Using full path to ArcObjects JAR file: %s", jarFile.getAbsolutePath()));
        } else {
            jarFile = null;
        }
    }

    if (jarFile == null) {
        String jarPath = arcObjectsHome + File.separator + "arcobjects.jar";
        jarFile = new File(jarPath);

        if (jarFile.exists()) {
            log.info(String.format("Using arcobjects.jar found in directory: %s", jarFile.getAbsolutePath()));
        } else {
            jarFile = null;
        }
    }

    if (jarFile == null) {
        String jarPath = arcObjectsHome + File.separator + "java" + File.separator + "lib" + File.separator
                + "arcobjects.jar";
        jarFile = new File(jarPath);

        if (!jarFile.exists()) {
            throw new Exception(
                    "Error: could not find arcobjects.jar at path \"" + jarFile.getAbsolutePath() + "\"");
        } else {
            log.info(String.format("Using ArcObjects home \"%s\"", arcObjectsHome));
        }
    }

    // Deze hack is afkomstig van ESRI voorbeelden...

    // Helps load classes and resources from a search path of URLs
    URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> sysclass = URLClassLoader.class;

    try {
        Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { jarFile.toURI().toURL() });
    } catch (Throwable throwable) {
        throw new Exception("Could not add arcobjects.jar to system classloader", throwable);
    }
}

From source file:com.haulmont.bali.util.ReflectionHelper.java

/**
 * Invokes a method by reflection.//from  w  w w.j a  v a 2 s .com
 * @param obj       object instance
 * @param name      method name
 * @param params    method arguments
 * @return          method result
 * @throws NoSuchMethodException if a suitable method not found
 */
public static <T> T invokeMethod(Object obj, String name, Object... params) throws NoSuchMethodException {
    Class[] paramTypes = getParamTypes(params);

    final Class<?> aClass = obj.getClass();
    Method method;
    try {
        method = aClass.getDeclaredMethod(name, paramTypes);
    } catch (NoSuchMethodException e) {
        method = aClass.getMethod(name, paramTypes);
    }
    method.setAccessible(true);
    try {
        //noinspection unchecked
        return (T) method.invoke(obj, params);
    } catch (IllegalAccessException | InvocationTargetException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

static Method getMethod(Class<?> clz, final String mtdName, Class<?>[] mtdArgs) {
    if (clz == null || TextUtils.isEmpty(mtdName) || mtdArgs == null) {
        return null;
    }//from   ww  w.  j av a  2s. c o  m
    Method mtd = null;
    try {
        mtd = clz.getDeclaredMethod(mtdName, mtdArgs);
        mtd.setAccessible(true);
    } catch (NoSuchMethodException e) {
        Log.d(TAG, e.getMessage(), e);
    }
    return mtd;
}

From source file:com.weibo.api.motan.protocol.grpc.GrpcUtil.java

public static MethodDescriptor.Marshaller getJsonMarshaller(Class clazz) {
    try {//w  w  w. j av a2s  .c o  m
        if (MessageLite.class.isAssignableFrom(clazz)) {
            Method method = clazz.getDeclaredMethod("getDefaultInstance", null);
            Message message = (Message) method.invoke(null, null);
            return jsonMarshaller(message);
        }
    } catch (Exception ignore) {
    }
    return null;
}

From source file:Main.java

@SuppressWarnings("all")
private static boolean setProxyICS(WebView webview, String host, int port) {
    try {/*from www. ja  va 2s .c o m*/
        Class jwcjb = Class.forName("android.webkit.JWebCoreJavaBridge");
        Class params[] = new Class[1];
        params[0] = Class.forName("android.net.ProxyProperties");
        Method updateProxyInstance = jwcjb.getDeclaredMethod("updateProxy", params);

        Class wv = Class.forName("android.webkit.WebView");
        Field mWebViewCoreField = wv.getDeclaredField("mWebViewCore");
        Object mWebViewCoreFieldInstance = getFieldValueSafely(mWebViewCoreField, webview);

        Class wvc = Class.forName("android.webkit.WebViewCore");
        Field mBrowserFrameField = wvc.getDeclaredField("mBrowserFrame");
        Object mBrowserFrame = getFieldValueSafely(mBrowserFrameField, mWebViewCoreFieldInstance);

        Class bf = Class.forName("android.webkit.BrowserFrame");
        Field sJavaBridgeField = bf.getDeclaredField("sJavaBridge");
        Object sJavaBridge = getFieldValueSafely(sJavaBridgeField, mBrowserFrame);

        Class ppclass = Class.forName("android.net.ProxyProperties");
        Class pparams[] = new Class[3];
        pparams[0] = String.class;
        pparams[1] = int.class;
        pparams[2] = String.class;
        Constructor ppcont = ppclass.getConstructor(pparams);
        updateProxyInstance.invoke(sJavaBridge, ppcont.newInstance(host, port, null));
        Log.d(LOG_TAG, "Setting proxy with 4.0 API successful!");
        return true;
    } catch (Exception ex) {
        Log.e(LOG_TAG, "failed to set HTTP proxy: " + ex);
        return false;
    }
}

From source file:biz.wolschon.finance.jgnucash.actions.FileBugInBrowserAction.java

/**
        /*from w  w w  .  ja v  a2 s.  co  m*/
 * Open the given URL in the default-browser.
 * @param url the URL to open
 * @return false if it did not work
 */
@SuppressWarnings("unchecked")
public static boolean showDocument(final URL url) {

    if (myJNLPServiceManagerObject == null) {
        myJNLPServiceManagerObject = getJNLPServiceManagerObject();
    }

    // we cannot use JNLP -> make an educated guess
    if (myJNLPServiceManagerObject == null) {
        try {
            String osName = System.getProperty("os.name");
            if (osName.startsWith("Mac OS")) {
                Class fileMgr = Class.forName("com.apple.eio.FileManager");
                Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
                openURL.invoke(null, new Object[] { url });
            } else if (osName.startsWith("Windows")) {
                Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
            } else { //assume Unix or Linux
                String[] browsers = { "x-www-browser", "firefox", "iceweasle", "opera", "konqueror", "epiphany",
                        "mozilla", "netscape" };
                String browser = null;
                for (int count = 0; count < browsers.length && browser == null; count++) {
                    if (Runtime.getRuntime().exec(new String[] { "which", browsers[count] }).waitFor() == 0) {
                        browser = browsers[count];
                    }
                    if (browser == null) {
                        return false;
                    } else {
                        Runtime.getRuntime().exec(new String[] { browser, url.toString() });
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error attempting to launch web browser natively.", e);
            JOptionPane.showMessageDialog(null,
                    "Error attempting to launch web browser:\n" + e.getLocalizedMessage());
        }
    }

    if (myJNLPServiceManagerObject != null) {
        try {
            Method method = myJNLPServiceManagerObject.getClass().getMethod("showDocument",
                    new Class[] { URL.class });
            Boolean resultBoolean = (Boolean) method.invoke(myJNLPServiceManagerObject, new Object[] { url });
            return resultBoolean.booleanValue();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null,
                    "Error attempting to launch web browser:\n" + ex.getLocalizedMessage());
        }
    }

    return false;
}

From source file:com.mindquarry.desktop.util.AutostartUtilities.java

public static void setAutostart(boolean autostart, Set<String> targetPatterns) {
    // check if we are on a Windows platform, otherwise skip processing
    boolean windows = SVNFileUtil.isWindows;
    if (!windows) {
        log.debug("not setting autostart, os is not windows: " + System.getProperty("os.name"));
        return;/*from   w  ww. j  ava 2s  .c om*/
    }
    log.debug("setting autostart, os: " + System.getProperty("os.name"));
    // registry variables

    // create registry method objects
    final Preferences userRoot = Preferences.userRoot();
    final Class<? extends Preferences> clz = userRoot.getClass();

    try {
        // define methods for registry manipulation
        final Method mOpenKey = clz.getDeclaredMethod("openKey", //$NON-NLS-1$
                new Class[] { byte[].class, int.class, int.class });
        mOpenKey.setAccessible(true);

        final Method mCloseKey = clz.getDeclaredMethod("closeKey", //$NON-NLS-1$
                new Class[] { int.class });
        mCloseKey.setAccessible(true);

        final Method mWinRegSetValue = clz.getDeclaredMethod("WindowsRegSetValueEx", //$NON-NLS-1$
                new Class[] { int.class, byte[].class, byte[].class });
        mWinRegSetValue.setAccessible(true);

        final Method mWinRegDeleteValue = clz.getDeclaredMethod("WindowsRegDeleteValue", //$NON-NLS-1$
                new Class[] { int.class, byte[].class });
        mWinRegDeleteValue.setAccessible(true);

        // open registry key
        Integer hSettings = (Integer) mOpenKey.invoke(userRoot, new Object[] { toByteArray(AUTOSTART_KEY),
                new Integer(KEY_ALL_ACCESS), new Integer(KEY_ALL_ACCESS) });

        // check autostart settings
        if (autostart) {
            // find classpath entry for desktop client JAR:
            String path = JarUtilities.getJar(targetPatterns);
            // write autostart value
            mWinRegSetValue.invoke(userRoot,
                    new Object[] { hSettings, toByteArray(AUTOSTART_ENTRY), toByteArray(path) });
        } else {
            // delete autostart entry
            mWinRegDeleteValue.invoke(userRoot, new Object[] { hSettings, toByteArray(AUTOSTART_ENTRY) });
        }
        // close registry key
        mCloseKey.invoke(Preferences.userRoot(), new Object[] { hSettings });
    } catch (Exception e) {
        // TODO: throw exception and catch it outside to display an error dialog
        log.error("Error while writing registry entries.", e); //$NON-NLS-1$
    }
}