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:com.apdplat.platform.compass.APDPlatLocalCompassBean.java

private Method findMethod(Class clazz, String methodName, Class... parameterTypes) {
    if (clazz.equals(Object.class)) {
        return null;
    }//from   w  ww . ja  v a2  s . c  o m
    try {
        return clazz.getDeclaredMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
        return findMethod(clazz.getSuperclass(), methodName, parameterTypes);
    }
}

From source file:com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheckTest.java

@Test
// UT uses Reflection to avoid removing null-validation from static method,
// which is a candidate for utility method in the future
public void testGetFullImportIdent() {
    Object actual;/*from  ww  w .  ja  va2 s  .  co  m*/
    try {
        Class<?> clazz = Class.forName("com.puppycrawl.tools.checkstyle.checks.imports.CustomImportOrderCheck");
        Object t = clazz.getConstructor().newInstance();
        Method method = clazz.getDeclaredMethod("getFullImportIdent", DetailAST.class);
        method.setAccessible(true);
        actual = method.invoke(t, (DetailAST) null);
    } catch (ClassNotFoundException | NoSuchMethodException | InstantiationException | IllegalAccessException
            | InvocationTargetException ignored) {
        actual = null;
    }

    String expected = "";
    assertEquals(expected, actual);
}

From source file:se.crisp.codekvast.agent.daemon.codebase.CodeBaseScanner.java

private Class findDeclaringClass(Class<?> clazz, Method method, Set<String> packages) {
    if (clazz == null) {
        return null;
    }/*w ww . j a  va  2 s .  c  o  m*/
    String pkg = clazz.getPackage().getName();

    boolean found = false;
    for (String prefix : packages) {
        if (pkg.startsWith(prefix)) {
            found = true;
            break;
        }
    }

    if (!found) {
        return null;
    }

    try {
        //noinspection ConfusingArgumentToVarargsMethod
        clazz.getDeclaredMethod(method.getName(), method.getParameterTypes());
        return clazz;
    } catch (NoSuchMethodException ignore) {
    }
    return findDeclaringClass(clazz.getSuperclass(), method, packages);
}

From source file:com.github.pith.typedconfig.TypedConfigPlugin.java

private Map<Class<Object>, Object> initConfigClasses(Collection<Class<?>> configClasses,
        Configuration configuration) {
    Map<Class<Object>, Object> configClassesMap = new HashMap<Class<Object>, Object>();

    for (Class<?> configClass : configClasses) {
        try {/*  www . j a v a 2  s .c  om*/
            Object configObject = configClass.newInstance();
            for (Method method : configClass.getDeclaredMethods()) {
                if (method.getName().startsWith("get")) {
                    Object property = configuration.getProperty(configClass.getSimpleName().toLowerCase()
                            + method.getName().substring(3).toLowerCase());
                    if (property != null) {
                        try {
                            Method setter = configClass.getDeclaredMethod("set" + method.getName().substring(3),
                                    method.getReturnType());
                            setter.setAccessible(true);
                            setter.invoke(configObject, property);
                        } catch (NoSuchMethodException e) {
                            throw new IllegalStateException("The TypedConfigPlugin can't initialize "
                                    + method.getName() + " because there is no associated setter.");
                        } catch (InvocationTargetException e) {
                            if (e.getCause() != null) {
                                throw new IllegalStateException("Failed to initialize " + method.getName(),
                                        e.getCause());
                            }
                        }
                    }
                }
            }
            //noinspection unchecked
            configClassesMap.put((Class<Object>) configClass, configObject);
        } catch (InstantiationException e) {
            throw new IllegalStateException("Failed to instantiate " + configClass, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Failed to access the constructor of " + configClass, e.getCause());
        }
    }
    return configClassesMap;
}

From source file:alpine.Config.java

/**
 * Extends the runtime classpath to include the files or directories specified.
 * @param files one or more File objects representing a single JAR file or a directory containing JARs.
 * @since 1.0.0//  w  ww . ja v a2 s . co  m
 */
public void expandClasspath(File... files) {
    URLClassLoader urlClassLoader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Class<URLClassLoader> urlClass = URLClassLoader.class;
    for (File file : files) {
        LOGGER.info("Expanding classpath to include: " + file.getAbsolutePath());
        URI fileUri = file.toURI();
        try {
            Method method = urlClass.getDeclaredMethod("addURL", URL.class);
            method.setAccessible(true);
            method.invoke(urlClassLoader, fileUri.toURL());
        } catch (MalformedURLException | NoSuchMethodException | IllegalAccessException
                | InvocationTargetException e) {
            LOGGER.error("Error expanding classpath", e);
        }
    }
}

From source file:org.acmsl.queryj.customsql.handlers.customsqlvalidation.BindQueryParametersHandler.java

/**
 * Retrieves the method to call./*w  ww .j a va2s .c om*/
 * @param instanceClass the instance class.
 * @param methodName the method name.
 * @param parameterClasses the parameter classes.
 * @return the <code>Method</code> instance.
 * @throws NoSuchMethodException if the method is not found.
 */
@NotNull
protected Method retrieveMethod(@NotNull final Class<?> instanceClass, @NotNull final String methodName,
        @NotNull final Class<?>[] parameterClasses) throws NoSuchMethodException {
    return instanceClass.getDeclaredMethod(methodName, parameterClasses);
}

From source file:biomine.bmvis2.Vis.java

private void openURL(String url) {
    if (url == null)
        return;/*w w w.  ja v a 2 s.c  o  m*/
    if (appletContext != null) {
        try {
            appletContext.showDocument(new URL(url), "_blank");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "Failed to open URL: " + url + "\n" + e.getMessage(),
                    "Error opening URL", JOptionPane.ERROR_MESSAGE);
        }
        return;
    }
    String os = System.getProperty("os.name");
    if (os.startsWith("Mac OS")) {
        try {
            Class fileMgr = Class.forName("com.apple.eio.FileManager");
            Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class });
            if (openURL != null)
                openURL.invoke(null);
        } catch (Exception e) {
            Logging.error("ui", "Error opening URL: " + e.getMessage());
        }
        return;
    }
    if (os.startsWith("Windows")) {
        try {
            Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url);
        } catch (Exception e) {
            Logging.error("ui", "Error opening URL: " + e.getMessage());
        }
        return;
    }
    // DEBUG: Assuming Firefox for everything not OS X or Windows
    try {
        Runtime.getRuntime().exec(new String[] { "firefox", "-remote", "openurl(" + url + ", new-tab)" });
    } catch (Exception e) {
        Logging.error("ui", "Error opening URL: " + e.getMessage());
    }
}

From source file:message.mybatis.common.mapper.MapperHelper.java

/**
 * Spring?,Spring4.x?/*from ww  w.  java  2  s  .c  o  m*/
 */
private void initSpringVersion() {
    try {
        //???SpringVersion
        Class<?> springVersionClass = Class.forName("org.springframework.core.SpringVersion");
        springVersion = (String) springVersionClass.getDeclaredMethod("getVersion", new Class<?>[0])
                .invoke(null, new Object[0]);
        spring = true;
        if (springVersion.indexOf(".") > 0) {
            int MajorVersion = Integer.parseInt(springVersion.substring(0, springVersion.indexOf(".")));
            if (MajorVersion > 3) {
                spring4 = true;
            } else {
                spring4 = false;
            }
        }
    } catch (Exception e) {
        spring = false;
        spring4 = false;
    }
}

From source file:com.example.android.network.sync.basicsyncadapter.SyncAdapter.java

/**
 * Given a string representation of a URL, sets up a connection and gets an input stream.
 *///from   w w w.  j a  v a2  s.  c om
private SyncResult doFetchAllForURL(Class sClass, SyncResult sResults) throws IOException {

    try {
        Method urlForFetchAllMethod = sClass.getDeclaredMethod("urlForFetchAll", null);
        String urlForFetchAll = (String) urlForFetchAllMethod.invoke(null, null);

        System.out.println(urlForFetchAll);
        final URL fetchAllURL = new URL(urlForFetchAll);

        HttpURLConnection conn = (HttpURLConnection) fetchAllURL.openConnection();
        conn.setRequestProperty("X-Parse-Application-Id", "TsEDR12ICJtD59JM92WslVurN0wh5JPuznKvroRc");
        conn.setRequestProperty("X-Parse-REST-API-Key", "4LC6oFNCyqLMFHSdPIPsxJoXHY6gTHGMG2kUcbwB");
        conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
        conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        Log.i(TAG, "Response from parse.com : " + conn.getResponseMessage());
        Log.i(TAG, "Status Code from parse.com : " + conn.getResponseCode());

        Class[] cArg = new Class[3];
        cArg[0] = Context.class;
        cArg[1] = InputStream.class;
        cArg[2] = SyncResult.class;

        Method handleDataForModel = sClass.getDeclaredMethod("handleInsertWithData", cArg);
        SyncResult objectsUpdated = (SyncResult) handleDataForModel.invoke(null, this.getContext(),
                conn.getInputStream(), sResults);
        return objectsUpdated;
    }

    catch (Exception ex) {
        Log.i(TAG, "exception " + ex.toString());
    }

    return sResults;
}