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:org.alfresco.test.PublicBeansBCKTest.java

@Test
public void testWorkflowBeans() {
    // ensure the required setters are still present
    Class<WorkflowDeployer> workflowDeployerClass = WorkflowDeployer.class;

    try {/*from w w w .ja  va 2s.c om*/
        Method setWorkflowDefinitionsMethod = workflowDeployerClass.getDeclaredMethod("setWorkflowDefinitions",
                new Class[] { List.class });
        assertNotNull("Expected to find setWorkflowDefinitions method on WorkflowDeployer",
                setWorkflowDefinitionsMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setWorkflowDefinitions method on WorkflowDeployer");
    }

    try {
        Method setModelsMethod = workflowDeployerClass.getDeclaredMethod("setModels",
                new Class[] { List.class });
        assertNotNull("Expected to find setModels method on WorkflowDeployer", setModelsMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setModels method on WorkflowDeployer");
    }

    try {
        Method setLabelsMethod = workflowDeployerClass.getDeclaredMethod("setLabels",
                new Class[] { List.class });
        assertNotNull("Expected to find setLabels method on WorkflowDeployer", setLabelsMethod);
    } catch (NoSuchMethodException error) {
        fail("Expected to find setLabels method on WorkflowDeployer");
    }

    // ensure the workflowDeployer abstract bean is still present
    assertTrue(beanDefinitionNames.contains("workflowDeployer"));
}

From source file:ch.jamiete.hilda.plugins.PluginManager.java

private boolean loadPlugin(final PluginData data) {
    if (this.isLoaded(data)) {
        return true;
    }// www  . j a  va 2 s. c  o m

    try {
        final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
        final Class<URLClassLoader> sysclass = URLClassLoader.class;
        final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(sysloader, new Object[] { data.pluginFile.toURI().toURL() });

        final Class<?> mainClass = Class.forName(data.mainClass);

        if (mainClass != null) {
            if (!HildaPlugin.class.isAssignableFrom(mainClass)) {
                Hilda.getLogger().severe("Could not load plugin " + data.getName()
                        + " because its main class did not implement HildaPlugin!");
                return false;
            }

            final HildaPlugin newPlugin = (HildaPlugin) mainClass.getConstructor(Hilda.class)
                    .newInstance(this.hilda);

            final Field pluginDataField = HildaPlugin.class.getDeclaredField("pluginData");
            pluginDataField.setAccessible(true);
            pluginDataField.set(newPlugin, data);

            this.plugins.add(newPlugin);

            try {
                newPlugin.onLoad();
            } catch (final Exception e) {
                Hilda.getLogger().log(Level.WARNING, "Encountered exception when calling load method of plugin "
                        + data.name + ". It may not have properly loaded and may cause errors.", e);
            }

            Hilda.getLogger().info("Loaded plugin " + data.name);
            return true;
        }
    } catch (final Exception ex) {
        Hilda.getLogger().log(Level.WARNING, "Encountered exception when loading plugin " + data.name, ex);
    }

    return false;
}

From source file:com.wabacus.system.dataset.update.precondition.DefaultConcreteExpressionBean.java

private Object getRealParamValueByClass(ReportRequest rrequest, Map<String, String> mRowData,
        Map<String, String> mParamValues, Class c) {
    try {//w  w w.  java  2s  .co  m
        Method m = c.getDeclaredMethod("getValue",
                new Class[] { ReportRequest.class, ReportBean.class, Map.class, Map.class });
        return m.invoke(c.newInstance(), new Object[] { rrequest, getReportBean(), mRowData, mParamValues });
    } catch (Exception e) {
        throw new WabacusRuntimeException("" + getReportBean().getPath()
                + "precondition?JAVA" + c.getName()
                + "getValue(ReportRequet,ReportBean,Map,Map)??", e);
    }
}

From source file:ch.shaktipat.saraswati.internal.common.AbstractStateMachine.java

/**
 * Invoke the no argument method with the following name.
 *
 * @param methodName The method to invoke.
 * @return Whether the invoke was successful.
 *//*from   w ww .  j  a v a  2  s .c om*/
public boolean invoke(final String methodName) {
    @SuppressWarnings("rawtypes")
    Class clas = this.getClass();
    try {
        @SuppressWarnings("unchecked")
        Method method = clas.getDeclaredMethod(methodName, SIGNATURE);
        method.invoke(this, PARAMETERS);
    } catch (SecurityException se) {
        logError(se);
        return false;
    } catch (NoSuchMethodException nsme) {
        logError(nsme);
        return false;
    } catch (IllegalArgumentException iae) {
        logError(iae);
        return false;
    } catch (IllegalAccessException iae) {
        logError(iae);
        return false;
    } catch (InvocationTargetException ite) {
        logError(ite);
        return false;
    }
    return true;
}

From source file:org.springmodules.cache.config.CacheSetupStrategyParserTests.java

private void setUpStrategyParser() throws Exception {
    Class targetClass = AbstractCacheSetupStrategyParser.class;

    Method getCacheModelKeyMethod = targetClass.getDeclaredMethod("getCacheModelKey", new Class[0]);

    Method parseCacheSetupStrategyMethod = targetClass.getDeclaredMethod("parseCacheSetupStrategy",
            new Class[] { Element.class, ParserContext.class, CacheSetupStrategyPropertySource.class });

    Method[] methodsToMock = { getCacheModelKeyMethod, parseCacheSetupStrategyMethod };

    strategyParserControl = MockClassControl.createControl(targetClass, null, null, methodsToMock);

    strategyParser = (AbstractCacheSetupStrategyParser) strategyParserControl.getMock();
    strategyParser.setBeanReferenceParser(beanReferenceParser);
    strategyParser.setCacheModelParser(modelParser);
    strategyParser.setCachingListenerValidator(validator);
}

From source file:it.cnr.icar.eric.server.plugin.AbstractPluginManager.java

/**
* Creates the instance of the pluginClass
*///from  w w w .  j a v a  2 s  . co  m
protected Object createPluginInstance(String pluginClass) throws Exception {
    Object plugin = null;

    if (log.isDebugEnabled()) {
        log.debug("pluginClass = " + pluginClass);
    }

    if (pluginClass != null) {
        Class<?> theClass = Class.forName(pluginClass);

        //try to invoke zero arg constructor using Reflection, 
        //if this fails then try invoking getInstance()
        try {
            Constructor<?> constructor = theClass.getConstructor((java.lang.Class[]) null);
            plugin = constructor.newInstance(new Object[0]);
        } catch (Exception e) {
            Method factory = theClass.getDeclaredMethod("getInstance", (java.lang.Class[]) null);
            plugin = factory.invoke((java.lang.Class[]) null, new Object[0]);
        }
    }
    return plugin;
}

From source file:com.qingstor.sdk.utils.QSJSONUtil.java

private static boolean initParameter(JSONObject o, Field[] declaredField, Class objClass, Object targetObj)
        throws NoSuchMethodException {
    boolean hasParam = false;
    for (Field field : declaredField) {
        String methodField = QSParamInvokeUtil.capitalize(field.getName());
        String getMethodName = field.getType() == Boolean.class ? "is" + methodField : "get" + methodField;
        String setMethodName = "set" + methodField;
        Method[] methods = objClass.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(getMethodName)) {
                ParamAnnotation annotation = m.getAnnotation(ParamAnnotation.class);
                if (annotation == null) {
                    continue;
                }//from w w  w  .  j  a  va 2 s  .  com
                String dataKey = annotation.paramName();

                if (o.has(dataKey)) {
                    hasParam = true;
                    Object data = toObject(o, dataKey);
                    Method setM = objClass.getDeclaredMethod(setMethodName, field.getType());
                    setParameterToMap(setM, targetObj, field, data);
                }
            }
        }
    }
    return hasParam;
}

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

/**
 * Retrieves the method to call./*from  w w  w  . ja v a 2s.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 does not exist.
 */
@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:com.t3.client.TabletopTool.java

/**
 * If we're running on OSX we should call this method to download and
 * install the TabletopTool logo from the main web site. We cache this image so
 * that it appears correctly if the application is later executed in
 * "offline" mode, so to speak.//from   ww  w  .  ja  va 2  s  .  c o  m
 */
private static void macOSXicon() {
    // If we're running on OSX, add the dock icon image
    // -- and change our application name to just "TabletopTool" (not currently)
    // We wait until after we call initialize() so that the asset and image managers
    // are configured.
    Image img = null;
    File logoFile = new File(AppUtil.getAppHome("config"), "tabletoptool-dock-icon.png");
    URL logoURL = null;
    try {
        logoURL = new URL("http://services.tabletoptool.com/logo_large.png");
    } catch (MalformedURLException e) {
        showError("Attemping to form URL -- shouldn't happen as URL is hard-coded", e);
    }
    try {
        img = ImageUtil.bytesToImage(FileUtils.readFileToByteArray(logoFile));
    } catch (IOException e) {
        log.debug("Attemping to read cached icon: " + logoFile, e);
        try {
            img = ImageUtil.bytesToImage(FileUtil.getBytes(logoURL));
            // If we did download the logo, save it to the 'config' dir for later use.
            BufferedImage bimg = ImageUtil.createCompatibleImage(img, img.getWidth(null), img.getHeight(null),
                    null);
            FileUtils.writeByteArrayToFile(logoFile, ImageUtil.imageToBytes(bimg, "png"));
            img = bimg;
        } catch (IOException e1) {
            log.warn("Cannot read '" + logoURL + "' or  cached '" + logoFile + "'; no dock icon", e1);
        }
    }
    /*
     * Unfortunately the next line doesn't allow Eclipse to compile the code
     * on anything but a Mac. Too bad because there's no problem at runtime
     * since this code wouldn't be executed an any machine *except* a Mac.
     * Sigh.
     * 
     * com.apple.eawt.Application appl =
     * com.apple.eawt.Application.getApplication();
     */
    try {
        Class<?> appClass = Class.forName("com.apple.eawt.Application");
        Method getApplication = appClass.getDeclaredMethod("getApplication", (Class[]) null);
        Object appl = getApplication.invoke(null, (Object[]) null);
        Method setDockIconImage = appl.getClass().getDeclaredMethod("setDockIconImage",
                new Class[] { java.awt.Image.class });
        // If we couldn't grab the image for some reason, don't set the dock bar icon!  Duh!
        if (img != null)
            setDockIconImage.invoke(appl, new Object[] { img });

        if (T3Util.isDebugEnabled()) {
            // For some reason Mac users don't like the dock badge icon.  But from a development standpoint I like seeing the
            // version number in the dock bar.  So we'll only include it when running with T3_DEV on the command line.
            Method setDockIconBadge = appl.getClass().getDeclaredMethod("setDockIconBadge",
                    new Class[] { java.lang.String.class });
            String vers = getVersion();
            vers = vers.substring(vers.length() - 2);
            vers = vers.replaceAll("[^0-9]", "0"); // Convert all non-digits to zeroes
            setDockIconBadge.invoke(appl, new Object[] { vers });
        }
    } catch (Exception e) {
        log.info(
                "Cannot find/invoke methods on com.apple.eawt.Application; use -X command line options to set dock bar attributes",
                e);
    }
}

From source file:jp.co.nemuzuka.core.controller.AbsController.java

/**
 * Method?./*w w w  .  j  a  v  a  2  s  .  c o  m*/
 * ????
 * ???????????
 * @param clazz Class
 * @param methodName ??
 * @param paramClass ?
 * @return 
 * @throws NoSuchMethodException ??????????????
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected Method getDeclaredMethod(Class clazz, String methodName, Class[] paramClass)
        throws NoSuchMethodException {
    Method target = null;
    try {
        target = clazz.getDeclaredMethod(methodName, paramClass);
    } catch (NoSuchMethodException e) {
        Class superClazz = clazz.getSuperclass();
        if (superClazz == null) {
            throw e;
        }
        return getDeclaredMethod(superClazz, methodName, paramClass);
    }
    return target;
}