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:edu.cornell.mannlib.vedit.controller.EditFrontController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String controllerName = request.getParameter("controller") + "RetryController";
    if (controllerName == null || controllerName.length() == 0) {
        log.error("doPost() found no controller parameter");
    }//w w  w. j a  v a 2s .c om
    Class controller = null;
    Object controllerInstance = null;
    try {
        controller = Class.forName(CONTROLLER_PKG + "." + controllerName);
        try {
            controllerInstance = controller.getConstructor((Class[]) null).newInstance((Object[]) null);
            ((HttpServlet) controllerInstance).init(getServletConfig());
        } catch (Exception e) {
            String errMsg = "doPost() could not instantiate specific " + "controller " + controllerName;
            log.error(errMsg, e);
            throw new RuntimeException(errMsg, e);
        }
    } catch (ClassNotFoundException e) {
        String errMsg = "doPost() could not find controller " + CONTROLLER_PKG + "." + controllerName;
        log.error(errMsg);
        throw new RuntimeException(errMsg);
    }
    Class[] args = new Class[2];
    args[0] = HttpServletRequest.class;
    args[1] = HttpServletResponse.class;
    try {
        Method meth = controller.getDeclaredMethod("doGet", args);
        Object[] methArgs = new Object[2];
        methArgs[0] = request;
        methArgs[1] = response;
        try {
            meth.invoke(controllerInstance, methArgs);
        } catch (IllegalAccessException e) {
            String errMsg = "doPost() encountered IllegalAccessException " + "while invoking " + controllerName;
            log.error(errMsg, e);
            throw new RuntimeException(errMsg, e);
        } catch (InvocationTargetException e) {
            String errMsg = "doPost() encountered InvocationTargetException " + "while invoking "
                    + controllerName;
            log.error(errMsg, e);
            throw new RuntimeException(errMsg, e);
        }
    } catch (NoSuchMethodException e) {
        log.error("could not find doPost() method in " + controllerName);
        throw new RuntimeException("could not find doPost() method in " + controllerName);
    }
}

From source file:org.telegram.ui.LaunchActivity.java

@SuppressWarnings("unchecked")
private void prepareForHideShowActionBar() {
    try {//ww w .  j a v  a  2  s  .c  o  m
        Class firstClass = getSupportActionBar().getClass();
        Class aClass = firstClass.getSuperclass();
        if (aClass == android.support.v7.app.ActionBar.class) {
            Method method = firstClass.getDeclaredMethod("setShowHideAnimationEnabled", boolean.class);
            method.invoke(getSupportActionBar(), false);
        } else {
            Field field = aClass.getDeclaredField("mActionBar");
            field.setAccessible(true);
            Method method = field.get(getSupportActionBar()).getClass()
                    .getDeclaredMethod("setShowHideAnimationEnabled", boolean.class);
            method.invoke(field.get(getSupportActionBar()), false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.liferay.alloy.util.TypeUtil.java

private boolean _hasMethod(String className, String methodName, String[] paramTypes) {

    Class<?> javaClass = _getClass(className);

    if (javaClass == null) {
        return false;
    }//  w  ww .ja  v  a  2s  . co m

    Class<?> superClass = javaClass.getSuperclass();

    while (superClass != null) {
        boolean superClassHasMethod = _hasMethod(superClass.getName(), methodName, paramTypes);

        if (superClassHasMethod) {
            return true;
        }

        superClass = superClass.getSuperclass();
    }

    Class<?>[] parameterTypes = new Class<?>[paramTypes.length];

    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = _getClass(paramTypes[i]);

        if (paramType == null) {
            return false;
        }

        parameterTypes[i] = paramType;
    }

    Method method = null;

    try {
        method = javaClass.getDeclaredMethod(methodName, parameterTypes);
    } catch (NoSuchMethodException e) {
        //System.out.println(e.getMessage());
    }

    return method != null;
}

From source file:com.diversityarrays.dalclient.DefaultDALClient.java

public DefaultDALClient(String baseUrl) {
    String s = baseUrl;// w ww .  j av  a 2 s  . c om
    if (!s.endsWith("/")) { //$NON-NLS-1$
        s = s + "/"; //$NON-NLS-1$
    }
    this.baseUrl = s;

    if (Boolean.getBoolean(DefaultDALClient.class.getName() + ".WANT_LOGGING")) { //$NON-NLS-1$
        try {
            Class<?> logFactoryClass = Class.forName("org.apache.commons.logging.LogFactory"); //$NON-NLS-1$
            Method getLogMethod = logFactoryClass.getDeclaredMethod("getLog", Class.class); //$NON-NLS-1$
            log = (Log) getLogMethod.invoke(null, DALClient.class);
            // log = LogFactory.getLog(DALClient.class);
        } catch (ClassNotFoundException e) {
        } catch (NoSuchMethodException e) {
        } catch (SecurityException e) {
        } catch (IllegalAccessException e) {
        } catch (IllegalArgumentException e) {
        } catch (InvocationTargetException e) {
        }
    }

    String httpFactoryClassName = System.getProperty(this.getClass().getName() + ".HTTP_FACTORY_CLASS_NAME"); //$NON-NLS-1$
    if (httpFactoryClassName == null) {
        if (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik")) { //$NON-NLS-1$ //$NON-NLS-2$
            httpFactoryClassName = "com.diversityarrays.dalclient.httpandroid.AndroidDalHttpFactory"; //$NON-NLS-1$
        } else {
            httpFactoryClassName = "com.diversityarrays.dalclient.httpimpl.DalHttpFactoryImpl"; //$NON-NLS-1$
        }
    }

    try {
        Class<?> httpFactoryClass = Class.forName(httpFactoryClassName);
        if (!DalHttpFactory.class.isAssignableFrom(httpFactoryClass)) {
            throw new RuntimeException("className '" //$NON-NLS-1$
                    + httpFactoryClassName + "' does not implement " //$NON-NLS-1$
                    + DalHttpFactory.class.getName());
        }
        dalHttpFactory = (DalHttpFactory) httpFactoryClass.newInstance();

    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }

}

From source file:com.aliyun.openservices.odps.console.utils.CommandParserUtils.java

public static void printHelpInfo(List<String> keywords) {
    Map<String, Integer> matched = new HashMap<String, Integer>() {
    };/*  w w  w .  j av a 2  s.  c  o  m*/
    List<String> allCommands = new ArrayList<String>();

    if (ecList == null) {
        ecList = PluginUtil.getExtendCommandList();
    }

    for (PluginPriorityCommand command : ecList) {
        allCommands.add(command.getCommandName());
    }

    for (String commandName : allCommands) {
        try {
            Class<?> commandClass = Class.forName(commandName, false, classLoader);
            Field tags_field = commandClass.getField(HELP_TAGS_FIELD);
            String[] tags = (String[]) tags_field.get(null);

            int count = 0;
            for (String tag : tags) {
                for (String keyword : keywords) {
                    if (tag.equalsIgnoreCase(keyword)) {
                        count++;
                        break;
                    }
                }
            }
            if (count != 0) {
                matched.put(commandName, count);
            }
        } catch (ClassNotFoundException e) {
            // Console??AssertionError
            //throw new AssertionError("Cannot find the command:" + commandName);
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            // Ignore
        } catch (IllegalAccessException e) {
            // Ignore
        }
    }

    // Print the help info of the command(s) whose tags match most keywords
    boolean found = false;
    System.out.println();
    for (int i = keywords.size(); i >= 1; i--) {
        for (Map.Entry<String, Integer> entry : matched.entrySet()) {
            if (i == entry.getValue()) {
                try {
                    Class<?> commandClass = Class.forName(entry.getKey(), false, classLoader);
                    Method printMethod = commandClass.getDeclaredMethod(HELP_PRINT_METHOD,
                            new Class<?>[] { PrintStream.class });
                    printMethod.invoke(null, System.out);
                    found = true;
                } catch (ClassNotFoundException e) {
                    // Console??AssertionError
                    throw new AssertionError("Cannot find the command:" + entry.getKey());
                } catch (NoSuchMethodException e) {
                    // Ignore
                } catch (IllegalAccessException e) {
                    // Ignore
                } catch (InvocationTargetException e) {
                    // Ignore
                }
            }
        }
        if (found) {
            break;
        }
    }
    System.out.println();
}

From source file:com.yahala.ui.LaunchActivity.java

@SuppressWarnings("unchecked") /* set actionbar animation*/
private void prepareForHideShowActionBar() {
    try {/*from   ww  w  .  j  ava2s. co  m*/
        Class firstClass = getSupportActionBar().getClass();
        Class aClass = firstClass.getSuperclass();
        if (aClass == ActionBar.class) {
            Method method = firstClass.getDeclaredMethod("setShowHideAnimationEnabled", boolean.class);
            method.invoke(getSupportActionBar(), false);
        } else {
            Field field = aClass.getDeclaredField("mActionBar");
            field.setAccessible(true);
            Method method = field.get(getSupportActionBar()).getClass()
                    .getDeclaredMethod("setShowHideAnimationEnabled", boolean.class);
            method.invoke(field.get(getSupportActionBar()), false);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.myfaces.custom.dojo.DojoUtils.java

/**
 * creates a dojoed attribute map upon the given array of attribute names
 *
 * @param facesContext//from   w  w  w  .java2  s.  co  m
 *            standard faces context used internally
 * @param attributeNames
 *            string array of traversable attribute names
 * @param component
 *            the source component with the values set
 * @return a map which resembles the attribute map for further processing
 */
public static Map getAttributeMap(FacesContext facesContext, String[] attributeNames, UIComponent component) {
    Log log = null;

    Class componentClass = component.getClass();
    Map returnMap = new HashMap();
    for (int cnt = 0; cnt < attributeNames.length; cnt++) {
        try {
            String attributeName = attributeNames[cnt];
            //the dojo attributes deal with different ids than the rest
            if (attributeName.equals("id") || attributeName.equals("widgetId")) {
                String calculatedId = DojoUtils.calculateWidgetId(facesContext, component);
                returnMap.put("id", calculatedId);
            } else {
                String attributeCasedName = attributeName.substring(0, 1).toUpperCase()
                        + attributeName.substring(1);
                String getForm = "get" + attributeCasedName; // to prevent multiple creating in finding
                String isForm = "is" + attributeCasedName; // to prevent multiple creating in finding
                Method m = null;
                // finding getter in hiearchy: try current class for "get" and "is" form, if NOT found, try superclass
                // doesn't use getMethod() to avoid walking whole hiearchy for wrong form in case of "is"
                // and getMethod() uses getSuperClass() anyway, so no performance hit this way + ability to invoke protected methods
                while ((componentClass != null) && (m == null)) {
                    m = componentClass.getDeclaredMethod(getForm, null);
                    if (m == null) {
                        // try alternative method name for dealing with Booleans
                        m = componentClass.getDeclaredMethod(isForm, null);
                    }
                    if (m == null) {
                        // load superclass
                        componentClass = componentClass.getSuperclass(); // null in case of componentClass == Object
                    }
                }
                if (m != null) {
                    Object execRetval = m.invoke(component, null);
                    if (execRetval != null)
                        returnMap.put(attributeName, execRetval);
                }
            }
        } catch (Exception e) {
            if (log == null)
                log = LogFactory.getLog(DojoUtils.class);
            // this should not happen but can
            log.error("getAttributeMap", e);
        }
    }
    return returnMap;
}

From source file:org.apache.cocoon.environment.AbstractEnvironment.java

/**
 * Resolve an entity.//w  w w. j a va  2 s  .co m
 * @deprecated Use the resolveURI methods instead
 */
public Source resolve(String systemId) throws ProcessingException, SAXException, IOException {
    Deprecation.logger.warn(
            "The method SourceResolver.resolve(String) is " + "deprecated. Use resolveURI(String) instead.");
    if (!this.initializedComponents) {
        initComponents();
    }

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Resolving '" + systemId + "' in context '" + this.context + "'");
    }

    if (systemId == null) {
        throw new SAXException("Invalid System ID");
    }

    // get the wrapper class - we don't want to import the wrapper directly
    // to avoid a direct dependency from the core to the deprecation package
    Class clazz;
    try {
        clazz = ClassUtils
                .loadClass("org.apache.cocoon.components.source.impl.AvalonToCocoonSourceInvocationHandler");
    } catch (Exception e) {
        throw new ProcessingException("The deprecated resolve() method of the environment was called."
                + "Please either update your code to use the new resolveURI() method or"
                + " install the deprecation support.", e);
    }

    if (null == avalonToCocoonSourceWrapper) {
        synchronized (getClass()) {
            try {
                avalonToCocoonSourceWrapper = clazz.getDeclaredMethod("createProxy",
                        new Class[] { ClassUtils.loadClass("org.apache.excalibur.source.Source"),
                                ClassUtils.loadClass("org.apache.excalibur.source.SourceResolver"),
                                ClassUtils.loadClass(Environment.class.getName()),
                                ClassUtils.loadClass(ComponentManager.class.getName()) });
            } catch (Exception e) {
                throw new ProcessingException("The deprecated resolve() method of the environment was called."
                        + "Please either update your code to use the new resolveURI() method or"
                        + " install the deprecation support.", e);
            }
        }
    }

    try {
        org.apache.excalibur.source.Source source = resolveURI(systemId);
        Source wrappedSource = (Source) avalonToCocoonSourceWrapper.invoke(clazz,
                new Object[] { source, this.sourceResolver, this, this.manager });
        return wrappedSource;
    } catch (SourceException se) {
        throw SourceUtil.handle(se);
    } catch (Exception e) {
        throw new ProcessingException("Unable to create source wrapper.", e);
    }
}

From source file:org.hfoss.posit.android.sync.Communicator.java

/**
 * Returns a list on name/value pairs for the Find.  Should work for Plugin Finds as
 * well as Basic Finds.  //from  ww  w  . ja v a 2 s .  c  o  m
 * @param find
 * @param clazz
 * @return
 */
private static List<NameValuePair> getNameValuePairs(Find find, Class clazz) {
    Field[] fields = clazz.getDeclaredFields();

    List<NameValuePair> nvp = new ArrayList<NameValuePair>();
    String methodName = "";
    String value = "";

    for (Field field : fields) {
        //         Log.i(TAG, "class= " + clazz + " field = " + field);
        if (!Modifier.isFinal(field.getModifiers())) {
            String key = field.getName();
            methodName = "get" + key.substring(0, 1).toUpperCase() + key.substring(1);
            value = "";

            try {
                Class returnType = clazz.getDeclaredMethod(methodName, null).getReturnType();
                if (returnType.equals(String.class))
                    value = (String) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null);
                else if (returnType.equals(int.class))
                    value = String.valueOf(
                            (Integer) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));
                else if (returnType.equals(double.class))
                    value = String.valueOf(
                            (Double) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));
                else if (returnType.equals(boolean.class))
                    value = String.valueOf(
                            (Boolean) clazz.getDeclaredMethod(methodName, null).invoke(find, (Object[]) null));

            } catch (IllegalArgumentException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (SecurityException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (IllegalAccessException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (InvocationTargetException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            } catch (NoSuchMethodException e) {
                Log.e(TAG, e + ": " + e.getMessage());
            }
            nvp.add(new BasicNameValuePair(key, value));
        }
    }
    return nvp;

}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * Release a previously allocated memory URL
 * //from   w w w  . j  a v a 2s . c o m
 * @param u
 *            the URL to release memory
 */
public static void releaseMemoryURL(final URL u) {
    try {
        final Class c = ClassLoader.getSystemClassLoader()
                .loadClass("org.allcolor.yahp.converter.CMemoryURLHandler");
        final Method m = c.getDeclaredMethod("releaseMemoryURL", new Class[] { URL.class });
        m.setAccessible(true);
        m.invoke(null, new Object[] { u });
    } catch (final Exception ignore) {
        ignore.printStackTrace();
    }
}