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.pandoragames.far.ui.swing.component.MacOSXMenuAdapter.java

/**
 * Instantiates the <code>Application</code> class and initialises <i>this</i>
 * as a Proxy for interface <code>ApplicationListener</code>. Wires the two together.
 *///  w  ww .jav a2  s .c  om
public MacOSXMenuAdapter() {
    // 1. get an instance of apples Application class
    Class applicationClass = null;
    try {
        applicationClass = Class.forName(CL_OSX_APP);
        macOSXApplication = applicationClass.newInstance();
    } catch (Exception x) {
        String message = x.getClass().getName() + " instantiating " + CL_OSX_APP + ": " + x.getMessage();
        logger.error(message);
        throw new IllegalStateException(message);
    }
    // 2. Make THIS a Proxy for an ApplicationListener instance
    try {
        Class applicationListenerClass = Class.forName(CL_OSX_APP_LSTR);
        applicationListenerProxy = Proxy.newProxyInstance(MacOSXMenuAdapter.class.getClassLoader(),
                new Class[] { applicationListenerClass }, this);
        Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener",
                new Class[] { applicationListenerClass });
        addListenerMethod.invoke(macOSXApplication, new Object[] { applicationListenerProxy });
    } catch (Exception x) {
        String message = x.getClass().getName() + " instantiating " + CL_OSX_APP_LSTR + ": " + x.getMessage();
        logger.error(message);
        throw new IllegalStateException(message);
    }
}

From source file:com.google.gwt.dev.shell.jetty.JettyLauncher.java

/**
 * This is a modified version of JreMemoryLeakPreventionListener.java found
 * in the Apache Tomcat project at//from w w w  . j a  va2s  . co m
 *
 * http://svn.apache.org/repos/asf/tomcat/trunk/java/org/apache/catalina/core/
 * JreMemoryLeakPreventionListener.java
 *
 * Relevant part of the Tomcat NOTICE, retrieved from
 * http://svn.apache.org/repos/asf/tomcat/trunk/NOTICE Apache Tomcat Copyright
 * 1999-2010 The Apache Software Foundation
 *
 * This product includes software developed by The Apache Software Foundation
 * (http://www.apache.org/).
 */
private void jreLeakPrevention(TreeLogger logger) {
    // Trigger a call to sun.awt.AppContext.getAppContext(). This will
    // pin the common class loader in memory but that shouldn't be an
    // issue.
    ImageIO.getCacheDirectory();

    /*
     * Several components end up calling: sun.misc.GC.requestLatency(long)
     *
     * Those libraries / components known to trigger memory leaks due to
     * eventual calls to requestLatency(long) are: -
     * javax.management.remote.rmi.RMIConnectorServer.start()
     */
    try {
        Class<?> clazz = Class.forName("sun.misc.GC");
        Method method = clazz.getDeclaredMethod("requestLatency", new Class[] { long.class });
        method.invoke(null, Long.valueOf(3600000));
    } catch (ClassNotFoundException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (SecurityException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (NoSuchMethodException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (IllegalArgumentException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (IllegalAccessException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    } catch (InvocationTargetException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.gcDaemonFail", e);
    }

    /*
     * Calling getPolicy retains a static reference to the context class loader.
     */
    try {
        // Policy.getPolicy();
        Class<?> policyClass = Class.forName("javax.security.auth.Policy");
        Method method = policyClass.getMethod("getPolicy");
        method.invoke(null);
    } catch (ClassNotFoundException e) {
        // Ignore. The class is deprecated.
    } catch (SecurityException e) {
        // Ignore. Don't need call to getPolicy() to be successful,
        // just need to trigger static initializer.
    } catch (NoSuchMethodException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (IllegalArgumentException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (IllegalAccessException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    } catch (InvocationTargetException e) {
        logger.log(TreeLogger.WARN, "jreLeakPrevention.authPolicyFail", e);
    }

    /*
     * Creating a MessageDigest during web application startup initializes the
     * Java Cryptography Architecture. Under certain conditions this starts a
     * Token poller thread with TCCL equal to the web application class loader.
     *
     * Instead we initialize JCA right now.
     */
    java.security.Security.getProviders();

    /*
     * Several components end up opening JarURLConnections without first
     * disabling caching. This effectively locks the file. Whilst more
     * noticeable and harder to ignore on Windows, it affects all operating
     * systems.
     *
     * Those libraries/components known to trigger this issue include: - log4j
     * versions 1.2.15 and earlier - javax.xml.bind.JAXBContext.newInstance()
     */

    // Set the default URL caching policy to not to cache
    try {
        // Doesn't matter that this JAR doesn't exist - just as long as
        // the URL is well-formed
        URL url = new URL("jar:file://dummy.jar!/");
        URLConnection uConn = url.openConnection();
        uConn.setDefaultUseCaches(false);
    } catch (MalformedURLException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.jarUrlConnCacheFail", e);
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.jarUrlConnCacheFail", e);
    }

    /*
     * Haven't got to the root of what is going on with this leak but if a web
     * app is the first to make the calls below the web application class loader
     * will be pinned in memory.
     */
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    try {
        factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        logger.log(TreeLogger.ERROR, "jreLeakPrevention.xmlParseFail", e);
    }
}

From source file:de.static_interface.sinklibrary.SinkLibrary.java

public void addJarToClasspath(URL url) throws Exception {
    URLClassLoader classLoader = (URLClassLoader) getClassLoader();
    Class<URLClassLoader> clazz = URLClassLoader.class;

    // Use reflection to access protected "addURL" method
    Method method = clazz.getDeclaredMethod("addURL", new Class[] { URL.class });
    method.setAccessible(true);/* w  w  w  .  ja va2 s  .c om*/
    method.invoke(classLoader, url);
}

From source file:eu.carrade.amaury.BallsOfSteel.BoSCommand.java

/**
 * Handles a command.//  w  ww  .  j a va2  s.  c o m
 * 
 * @param sender The sender
 * @param command The executed command
 * @param label The alias used for this command
 * @param args The arguments given to the command
 * 
 * @author Amaury Carrade
 */
@SuppressWarnings("rawtypes")
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {

    boolean ourCommand = false;
    for (String commandName : p.getDescription().getCommands().keySet()) {
        if (commandName.equalsIgnoreCase(command.getName())) {
            ourCommand = true;
            break;
        }
    }

    if (!ourCommand) {
        return false;
    }

    /** Team chat commands **/

    if (command.getName().equalsIgnoreCase("t")) {
        doTeamMessage(sender, command, label, args);
        return true;
    }
    if (command.getName().equalsIgnoreCase("g")) {
        doGlobalMessage(sender, command, label, args);
        return true;
    }
    if (command.getName().equalsIgnoreCase("togglechat")) {
        doToggleTeamChat(sender, command, label, args);
        return true;
    }

    if (args.length == 0) {
        help(sender, args, false);
        return true;
    }

    String subcommandName = args[0].toLowerCase();

    // First: subcommand existence.
    if (!this.commands.contains(subcommandName)) {
        try {
            Integer.valueOf(subcommandName);
            help(sender, args, false);
        } catch (NumberFormatException e) { // If the subcommand isn't a number, it's an error.
            help(sender, args, true);
        }
        return true;
    }

    // Second: is the sender allowed?
    if (!isAllowed(sender, subcommandName)) {
        unauthorized(sender, command);
        return true;
    }

    // Third: instantiation
    try {
        Class<? extends BoSCommand> cl = this.getClass();
        Class[] parametersTypes = new Class[] { CommandSender.class, Command.class, String.class,
                String[].class };

        Method doMethod = cl.getDeclaredMethod("do" + WordUtils.capitalize(subcommandName), parametersTypes);

        doMethod.invoke(this, new Object[] { sender, command, label, args });

        return true;

    } catch (NoSuchMethodException e) {
        // Unknown method => unknown subcommand.
        help(sender, args, true);
        return true;

    } catch (SecurityException | IllegalAccessException | IllegalArgumentException
            | InvocationTargetException e) {
        sender.sendMessage(i.t("cmd.errorLoad"));
        e.printStackTrace();
        return false;
    }
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Returns true if indicated type matches the JAX-RPC enumeration class.
 * Note: supports JSR 101 version 0.6 Public Draft
 *
 * @param cls//from   ww  w .  j a  va 2s .  c om
 * @return
 */
public static boolean isEnumClass(Class cls) {

    try {
        java.lang.reflect.Method m = cls.getMethod("getValue", null);
        java.lang.reflect.Method m2 = cls.getMethod("toString", null);

        if ((m != null) && (m2 != null)) {
            java.lang.reflect.Method m3 = cls.getDeclaredMethod("fromString",
                    new Class[] { java.lang.String.class });
            java.lang.reflect.Method m4 = cls.getDeclaredMethod("fromValue", new Class[] { m.getReturnType() });

            if ((m3 != null) && Modifier.isStatic(m3.getModifiers()) && Modifier.isPublic(m3.getModifiers())
                    && (m4 != null) && Modifier.isStatic(m4.getModifiers())
                    && Modifier.isPublic(m4.getModifiers())) {

                // Return false if there is a setValue member method
                try {
                    if (cls.getMethod("setValue", new Class[] { m.getReturnType() }) == null) {
                        return true;
                    }

                    return false;
                } catch (java.lang.NoSuchMethodException e) {
                    return true;
                }
            }
        }
    } catch (java.lang.NoSuchMethodException e) {
    }

    return false;
}

From source file:org.apache.hadoop.hbase.regionserver.wal.FSHLog.java

/**
 * Find the 'getNumCurrentReplicas' on the passed <code>os</code> stream.
 * @return Method or null./*from  ww  w.  j a  v a2 s.c  o m*/
 */
private static Method getGetNumCurrentReplicas(final FSDataOutputStream os) {
    // TODO: Remove all this and use the now publically available
    // HdfsDataOutputStream#getCurrentBlockReplication()
    Method m = null;
    if (os != null) {
        Class<? extends OutputStream> wrappedStreamClass = os.getWrappedStream().getClass();
        try {
            m = wrappedStreamClass.getDeclaredMethod("getNumCurrentReplicas", new Class<?>[] {});
            m.setAccessible(true);
        } catch (NoSuchMethodException e) {
            LOG.info("FileSystem's output stream doesn't support getNumCurrentReplicas; "
                    + "HDFS-826 not available; fsOut=" + wrappedStreamClass.getName());
        } catch (SecurityException e) {
            LOG.info("No access to getNumCurrentReplicas on FileSystems's output stream; HDFS-826 "
                    + "not available; fsOut=" + wrappedStreamClass.getName(), e);
            m = null; // could happen on setAccessible()
        }
    }
    if (m != null) {
        if (LOG.isTraceEnabled())
            LOG.trace("Using getNumCurrentReplicas");
    }
    return m;
}

From source file:com.madrobot.di.wizard.json.JSONDeserializer.java

/**
 * Deserialize a specific element, recursively.
 * //  w ww  . j a  v  a  2s . c  o m
 * @param obj
 *            Object whose fields need to be set
 * @param jsonObject
 *            JSON Parser to read data from
 * @param stack
 *            Stack of {@link ClassInfo} - entity type under consideration
 * @throws JSONException
 *             If an exception occurs during parsing
 */
private void deserialize(Object obj, JSONObject jsonObject, Stack<Class<?>> stack) throws JSONException {

    Iterator<?> iterator = jsonObject.keys();
    Class<?> userClass = stack.peek();

    while (iterator.hasNext()) {
        Object jsonKey = iterator.next();

        if (jsonKey instanceof String) {
            String key = (String) jsonKey;
            Object jsonElement = jsonObject.get(key);

            try {

                Field field = getField(userClass, key);
                String fieldName = field.getName();
                Class<?> classType = field.getType();

                if (jsonElement instanceof JSONObject) {
                    if (!Converter.isPseudoPrimitive(classType)) {

                        String setMethodName = getSetMethodName(fieldName, classType);
                        Method setMethod = userClass.getDeclaredMethod(setMethodName, classType);

                        JSONObject fieldObject = (JSONObject) jsonElement;

                        stack.push(classType);
                        Object itemObj = classType.newInstance();
                        deserialize(itemObj, fieldObject, stack);

                        setMethod.invoke(obj, itemObj);
                    } else {
                        Log.e(TAG, "Expecting composite type for " + fieldName);
                    }
                } else if (jsonElement instanceof JSONArray) {
                    if (Converter.isCollectionType(classType)) {
                        if (field.isAnnotationPresent(ItemType.class)) {
                            ItemType itemType = field.getAnnotation(ItemType.class);
                            Class<?> itemValueType = itemType.value();
                            int size = itemType.size();

                            JSONArray fieldArrayObject = (JSONArray) jsonElement;

                            if (size == JSONDeserializer.DEFAULT_ITEM_COLLECTION_SIZE
                                    || size > fieldArrayObject.length()) {
                                size = fieldArrayObject.length();
                            }

                            for (int index = 0; index < size; index++) {
                                Object value = fieldArrayObject.get(index);
                                if (value instanceof JSONObject) {
                                    stack.push(itemValueType);
                                    Object itemObj = itemValueType.newInstance();
                                    deserialize(itemObj, (JSONObject) value, stack);

                                    String addMethodName = getAddMethodName(fieldName);
                                    Method addMethod = userClass.getDeclaredMethod(addMethodName,
                                            itemValueType);
                                    addMethod.invoke(obj, itemObj);
                                }
                            }
                        }
                    } else {
                        Log.e(TAG, "Expecting collection type for " + fieldName);
                    }
                } else if (Converter.isPseudoPrimitive(classType)) {

                    Object value = Converter.convertTo(jsonObject, key, classType, field);

                    String setMethodName = getSetMethodName(fieldName, classType);
                    Method setMethod = userClass.getDeclaredMethod(setMethodName, classType);
                    setMethod.invoke(obj, value);
                } else {
                    Log.e(TAG, "Unknown datatype");
                }

            } catch (NoSuchFieldException e) {
                Log.e(TAG, e.getMessage());
            } catch (NoSuchMethodException e) {
                Log.e(TAG, e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e.getMessage());
            } catch (InstantiationException e) {
                Log.e(TAG, e.getMessage());
            }
        }
    }
}

From source file:org.pmp.budgeto.app.SwaggerDispatcherConfigTest.java

@Test
public void springConf() throws Exception {

    Class<?> clazz = swaggerDispatcherConfig.getClass();
    Assertions.assertThat(clazz.getAnnotations()).hasSize(4);
    Assertions.assertThat(clazz.isAnnotationPresent(Configuration.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableWebMvc.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableSwagger.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(ComponentScan.class)).isTrue();
    Assertions.assertThat(clazz.getAnnotation(ComponentScan.class).basePackages())
            .containsExactly("com.ak.swaggerspringmvc.shared.app", "com.ak.spring3.music");

    Field fSpringSwaggerConfig = clazz.getDeclaredField("springSwaggerConfig");
    Assertions.assertThat(fSpringSwaggerConfig.getAnnotations()).hasSize(1);
    Assertions.assertThat(fSpringSwaggerConfig.isAnnotationPresent(Autowired.class)).isTrue();

    Method mCustomImplementation = clazz.getDeclaredMethod("customImplementation", new Class[] {});
    Assertions.assertThat(mCustomImplementation.getAnnotations()).hasSize(1);
    Assertions.assertThat(mCustomImplementation.getAnnotation(Bean.class)).isNotNull();
}

From source file:gov.nih.nci.system.web.struts.action.CreateAction.java

private void setParameterValue(Class klass, Object instance, String name, String value)
        throws NumberFormatException, Exception {
    if (value != null && value.trim().length() == 0)
        value = null;/*from w w w .  j a v  a 2 s  .c  o  m*/

    try {
        String paramName = name.substring(0, 1).toUpperCase() + name.substring(1);
        Method[] allMethods = klass.getMethods();
        for (Method m : allMethods) {
            String mname = m.getName();
            if (mname.equals("get" + paramName)) {
                Class type = m.getReturnType();
                Class[] argTypes = new Class[] { type };

                Method method = null;
                while (klass != Object.class) {
                    try {
                        Method setMethod = klass.getDeclaredMethod("set" + paramName, argTypes);
                        setMethod.setAccessible(true);
                        Object converted = convertValue(type, value);
                        if (converted != null)
                            setMethod.invoke(instance, converted);
                        break;
                    } catch (NumberFormatException e) {
                        throw e;
                    } catch (NoSuchMethodException ex) {
                        klass = klass.getSuperclass();
                    } catch (Exception e) {
                        throw e;
                    }
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:me.barrasso.android.volume.activities.ConfigurationActivity.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private void invokeFragmentManagerNoteStateNotSaved() {
    // For post-Honeycomb devices
    if (Build.VERSION.SDK_INT < 11) {
        return;/*from  w w w.j a  v a2  s  .  c om*/
    }
    try {
        Class<?> cls = getClass();
        do {
            cls = cls.getSuperclass();
        } while (!"Activity".equals(cls.getSimpleName()));
        Field fragmentMgrField = cls.getDeclaredField("mFragments");
        fragmentMgrField.setAccessible(true);

        Object fragmentMgr = fragmentMgrField.get(this);
        cls = fragmentMgr.getClass();

        Method noteStateNotSavedMethod = cls.getDeclaredMethod("noteStateNotSaved", new Class[] {});
        noteStateNotSavedMethod.invoke(fragmentMgr);
    } catch (Exception ex) {
        LOGE(TAG, "Error on FM.noteStateNotSaved", ex);
    }
}