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.github.helenusdriver.driver.impl.FieldInfoImpl.java

/**
 * Finds the setter method from the declaring class suitable to set a
 * value for the field.//from  w  w  w.  ja  va2 s  .c  om
 *
 * @author paouelle
 *
 * @param  declaringClass the non-<code>null</code> class declaring the field
 * @return the setter method for the field or <code>null</code> if none found
 * @throws IllegalArgumentException if unable to find a suitable setter
 */
private Method findSetterMethod(Class<?> declaringClass) {
    final String mname = "set" + WordUtils.capitalize(name, '_', '-');

    try {
        final Method m = declaringClass.getDeclaredMethod(mname, type);
        final int mods = m.getModifiers();

        if (Modifier.isAbstract(mods) || Modifier.isStatic(mods)) {
            return null;
        }
        org.apache.commons.lang3.Validate.isTrue(m.getParameterCount() == 1,
                "expecting setter for field '%s' with one parameter", field);
        final Class<?> wtype = ClassUtils.primitiveToWrapper(type);
        final Class<?> wptype = ClassUtils.primitiveToWrapper(DataTypeImpl.unwrapOptionalIfPresent(
                m.getParameterTypes()[0], m.getParameters()[0].getParameterizedType()));

        org.apache.commons.lang3.Validate.isTrue(wtype.isAssignableFrom(wptype),
                "expecting setter for field '%s' with parameter type: %s", field, type.getName());
        m.setAccessible(true);
        return m;
    } catch (NoSuchMethodException e) {
        return null;
    }
}

From source file:com.mobile.system.db.abatis.AbatisService.java

public Object parseToObject(Class beanClass, Cursor cur)
        throws IllegalAccessException, InstantiationException, SecurityException, NoSuchMethodException {
    Object obj = null;//from   ww w .java2 s  . c o m
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }

        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type

        Class[] parms = { type };
        Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
        m.setAccessible(true);
        // Set value
        try {
            int curIdx = cur.getColumnIndex(fieldName);
            if (curIdx != -1) {
                int nDotIdx = typeName.lastIndexOf(".");
                if (nDotIdx >= 0) {
                    typeName = typeName.substring(nDotIdx);
                }

                if (typeName.equals("int")) {
                    m.invoke(obj, cur.getInt(curIdx));
                } else if (typeName.equals("double")) {
                    m.invoke(obj, cur.getDouble(curIdx));
                } else if (typeName.equals("String")) {
                    m.invoke(obj, cur.getString(curIdx));
                } else if (typeName.equals("long")) {
                    m.invoke(obj, cur.getLong(curIdx));
                } else if (typeName.equals("float")) {
                    m.invoke(obj, cur.getFloat(curIdx));
                } else if (typeName.equals("Date")) {
                    m.invoke(obj, cur.getString(curIdx));
                } else if (typeName.equals("byte[]") || typeName.equals("[B")) {
                    m.invoke(obj, cur.getBlob(curIdx));
                } else {
                    m.invoke(obj, cur.getString(curIdx));
                }
            }

        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
        }
    }
    return obj;
}

From source file:com.adito.server.Main.java

private void doAddContextLoaderURL(URL u) {
    try {/*from  w  ww .  jav  a 2 s.  co  m*/
        Class sysclass = URLClassLoader.class;
        Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
        method.setAccessible(true);
        method.invoke(webappContext.getClassLoader(), new Object[] { u });
        if (log.isInfoEnabled())
            log.info(u.toExternalForm() + " added to context classloader");
    } catch (Exception e) {
        log.error("Failed to add to classpath.", e);
    }
}

From source file:com.openerp.orm.ORM.java

/**
 * Gets the dB helper from module.//w  w w  . j a  v  a  2  s.  com
 * 
 * @param module
 *            the module
 * @return the dB helper from module
 */
private BaseDBHelper getDBHelperFromModule(Module module) {
    Class newClass;
    try {
        newClass = Class.forName(module.getModuleInstance().getClass().getName());
        if (newClass.isInstance(module.getModuleInstance())) {
            Object receiver = newClass.newInstance();
            Class params[] = new Class[1];
            params[0] = Context.class;

            Method method = newClass.getDeclaredMethod("databaseHelper", params);

            Object obj = method.invoke(receiver, this.context);
            return (BaseDBHelper) obj;
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

From source file:hoot.services.controllers.job.JobResource.java

private JSONObject execReflectionSync(String jobId, String childJobId, JSONObject job,
        JobStatusManager jobStatusManager) throws Exception {
    String className = job.get("class").toString();
    String methodName = job.get("method").toString();

    String internalJobId = (job.get("internaljobid") == null) ? null : job.get("internaljobid").toString();

    JSONArray paramsList = (JSONArray) job.get("params");

    Class<?>[] paramTypes = new Class[paramsList.size()];
    Object[] parameters = new Object[paramsList.size()];
    for (int i = 0; i < paramsList.size(); i++) {
        JSONObject param = (JSONObject) paramsList.get(i);
        String paramType = param.get("paramtype").toString();
        Object oIsPrim = param.get("isprimitivetype");
        if ((oIsPrim != null) && oIsPrim.toString().equalsIgnoreCase("true")) {
            Class<?> classWrapper = Class.forName(paramType);
            paramTypes[i] = (Class<?>) classWrapper.getField("TYPE").get(null);
        } else {/*from   w w  w .  j av a 2s .  co m*/
            paramTypes[i] = Class.forName(paramType);
        }
        parameters[i] = param.get("value");
    }

    Class<?> clazz = Class.forName(className);
    Object instance = clazz.newInstance();

    JSONObject childJobInfo;
    String currentChildJobId = childJobId;

    // May be we would need create interface to guarranttee that it will
    // return a job id?  Add internal job id to end of method call
    if (internalJobId != null) {
        currentChildJobId = internalJobId;
        childJobInfo = createChildInfo(currentChildJobId, JOB_STATUS.RUNNING.toString());
        setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing");
        jobStatusManager.updateJob(jobId, jobInfo.toString());

        Object[] newParams = new Object[paramsList.size() + 1];
        System.arraycopy(parameters, 0, newParams, 0, parameters.length);
        newParams[parameters.length] = internalJobId;

        Class<?>[] newParamTypes = new Class[paramsList.size() + 1];
        System.arraycopy(paramTypes, 0, newParamTypes, 0, paramsList.size());
        newParamTypes[parameters.length] = String.class;
        Method method = clazz.getDeclaredMethod(methodName, newParamTypes);
        // This will blow if the method is not designed to handle job id
        method.invoke(instance, newParams);
    } else {
        Method method = clazz.getDeclaredMethod(methodName, paramTypes);
        Object oReflectJobId = method.invoke(instance, parameters);
        if (oReflectJobId != null) {
            currentChildJobId = oReflectJobId.toString();
        }

        // Updating job status info. Looks like we need to wait till job is
        // done to get job id. With this we can not canel..
        childJobInfo = createChildInfo(currentChildJobId, JobStatusManager.JOB_STATUS.RUNNING.toString());
        setJobInfo(jobInfo, childJobInfo, childrenInfo, JOB_STATUS.RUNNING.toString(), "processing");
        jobStatusManager.updateJob(jobId, jobInfo.toString());
    }

    return childJobInfo;
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Fill in a service description by introspecting the implementation
 * class.//from   w w  w. ja  v  a2 s . c o  m
 */
public void loadServiceDescByIntrospection(Class implClass) {
    if (introspectionComplete || implClass == null) {
        return;
    }

    // set the implementation class for the service description
    this.implClass = implClass;
    if (Skeleton.class.isAssignableFrom(implClass)) {
        isSkeletonClass = true;
        loadSkeletonOperations();
    }

    /** If the class knows what it should be exporting,
    * respect its wishes.
    */
    AxisServiceConfig axisConfig = null;
    try {
        Method method = implClass.getDeclaredMethod("getAxisServiceConfig", new Class[] {});
        if (method != null && Modifier.isStatic(method.getModifiers())) {
            axisConfig = (AxisServiceConfig) method.invoke(null, null);
        }
    } catch (Exception e) {
        // No problem, just continue without...
    }

    if (axisConfig != null) {
        String allowedMethodsStr = axisConfig.getAllowedMethods();
        if (allowedMethodsStr != null && !"*".equals(allowedMethodsStr)) {
            ArrayList methodList = new ArrayList();
            StringTokenizer tokenizer = new StringTokenizer(allowedMethodsStr, " ,");
            while (tokenizer.hasMoreTokens()) {
                methodList.add(tokenizer.nextToken());
            }
            setAllowedMethods(methodList);
        }
    }

    loadServiceDescByIntrospectionRecursive(implClass);

    // All operations should now be synchronized.  Check it.
    for (Iterator iterator = operations.iterator(); iterator.hasNext();) {
        OperationDesc operation = (OperationDesc) iterator.next();
        if (operation.getMethod() == null) {
            throw new InternalException(Messages.getMessage("badWSDDOperation", operation.getName(),
                    "" + operation.getNumParams()));
        }
    }

    if ((style == Style.MESSAGE) && operations.size() == 1) {
        messageServiceDefaultOp = (OperationDesc) operations.get(0);
    }

    introspectionComplete = true;
}

From source file:org.openmrs.module.sync.SyncUtil.java

/**
 * Rebuilds XSN form. This is needed for ingest when form is received from remote server;
 * template files that are contained in xsn in fromentry_xsn table need to be updated. Supported
 * way to do this is to ask formentry module to rebuild XSN. Invoking method via reflection is
 * temporary workaround until sync is in trunk: at that point advice point should be registered
 * on sync service that formentry could respond to by calling rebuild.
 * /*ww  w  .ja va2  s .co m*/
 * @param xsn the xsn to be rebuilt.
 */
public static void rebuildXSN(OpenmrsObject xsn) {
    Class c = null;
    Method m = null;
    String msg = null;

    if (xsn == null) {
        return;
    }

    try {
        // only rebuild non-archived xsns
        try {
            m = xsn.getClass().getDeclaredMethod("getArchived");
        } catch (Exception e) {
        }
        if (m == null) {
            log.warn("Failed to retrieve handle to getArchived method; is formentry module loaded?");
            return;
        }
        Boolean isArchived = (Boolean) m.invoke(xsn, null);

        if (isArchived)
            return;

        // get the form id of the xsn
        try {
            m = xsn.getClass().getDeclaredMethod("getForm");
        } catch (Exception e) {
        }
        if (m == null) {
            log.warn(
                    "Failed to retrieve handle to getForm method in FormEntryXsn; is formentry module loaded?");
            return;
        }
        Form form = (Form) m.invoke(xsn, null);

        msg = "Processing form with id: " + form.getFormId();

        // now get methods to rebuild the form
        try {
            c = Context.loadClass("org.openmrs.module.formentry.FormEntryUtil");
        } catch (Exception e) {
        }
        if (c == null) {
            log.warn(
                    "Failed to retrieve handle to FormEntryUtil in formentry module; is formentry module loaded? "
                            + msg);
            return;
        }

        try {
            m = c.getDeclaredMethod("rebuildXSN", new Class[] { Form.class });
        } catch (Exception e) {
        }
        if (m == null) {
            log.warn(
                    "Failed to retrieve handle to rebuildXSN method in FormEntryUtil; is formentry module loaded? "
                            + msg);
            return;
        }

        // finally actually do the rebuilding
        m.invoke(null, form);

    } catch (Exception e) {
        log.error("FormEntry module present but failed to rebuild XSN, see stack for error detail." + msg, e);
        throw new SyncException(
                "FormEntry module present but failed to rebuild XSN, see server log for the stacktrace for error details "
                        + msg,
                e);
    }
    return;
}

From source file:com.mobile.system.db.abatis.AbatisService.java

/**
 * /*w ww. j  av a  2s.c o  m*/
 * @param jsonStr
 *            JSON String
 * @param beanClass
 *            Bean class
 * @param basePackage
 *            Base package name which includes all Bean classes
 * @return Object Bean
 * @throws Exception
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object parse(String jsonStr, Class beanClass, String basePackage) throws Exception {
    Object obj = null;
    JSONObject jsonObj = new JSONObject(jsonStr);
    // Check bean object
    if (beanClass == null) {
        Log.d(TAG, "Bean class is null");
        return null;
    }
    // Read Class member fields
    Field[] props = beanClass.getDeclaredFields();
    if (props == null || props.length == 0) {
        Log.d(TAG, "Class" + beanClass.getName() + " has no fields");
        return null;
    }
    // Create instance of this Bean class
    obj = beanClass.newInstance();
    // Set value of each member variable of this object
    for (int i = 0; i < props.length; i++) {
        String fieldName = props[i].getName();
        // Skip public and static fields
        if (props[i].getModifiers() == (Modifier.PUBLIC | Modifier.STATIC)) {
            continue;
        }
        // Date Type of Field
        Class type = props[i].getType();
        String typeName = type.getName();
        // Check for Custom type
        if (typeName.equals("int")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getInt(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("long")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getLong(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.lang.String")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getString(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("double")) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                m.invoke(obj, jsonObj.getDouble(fieldName));
            } catch (Exception ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else if (typeName.equals("java.util.Date")) { // modify

            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);

            String dateString = jsonObj.getString(fieldName);
            dateString = dateString.replace(" KST", "");
            SimpleDateFormat genderFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.KOREA);
            // Set value
            try {
                Date afterDate = genderFormat.parse(dateString);
                m.invoke(obj, afterDate);
            } catch (Exception e) {
                Log.d(TAG, e.getMessage());
            }
        } else if (type.getName().equals(List.class.getName())
                || type.getName().equals(ArrayList.class.getName())) {
            // Find out the Generic
            String generic = props[i].getGenericType().toString();
            if (generic.indexOf("<") != -1) {
                String genericType = generic.substring(generic.lastIndexOf("<") + 1, generic.lastIndexOf(">"));
                if (genericType != null) {
                    JSONArray array = null;
                    try {
                        array = jsonObj.getJSONArray(fieldName);
                    } catch (Exception ex) {
                        Log.d(TAG, ex.getMessage());
                        array = null;
                    }
                    if (array == null) {
                        continue;
                    }
                    ArrayList arrayList = new ArrayList();
                    for (int j = 0; j < array.length(); j++) {
                        arrayList.add(parse(array.getJSONObject(j).toString(), Class.forName(genericType),
                                basePackage));
                    }
                    // Set value
                    Class[] parms = { type };
                    Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
                    m.setAccessible(true);
                    m.invoke(obj, arrayList);
                }
            } else {
                // No generic defined
                generic = null;
            }
        } else if (typeName.startsWith(basePackage)) {
            Class[] parms = { type };
            Method m = beanClass.getDeclaredMethod(getBeanMethodName(fieldName, 1), parms);
            m.setAccessible(true);
            // Set value
            try {
                JSONObject customObj = jsonObj.getJSONObject(fieldName);
                if (customObj != null) {
                    m.invoke(obj, parse(customObj.toString(), type, basePackage));
                }
            } catch (JSONException ex) {
                Log.d(TAG, ex.getMessage());
            }
        } else {
            // Skip
            Log.d(TAG, "Field " + fieldName + "#" + typeName + " is skip");
        }
    }
    return obj;
}

From source file:me.azenet.UHPlugin.UHPluginCommand.java

/**
 * Handles a command./*  w w  w. ja  v  a 2 s. c om*/
 * 
 * @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;
    }

    /** /join & /leave commands **/

    if (command.getName().equalsIgnoreCase("join")) {
        doJoin(sender, command, label, args);
        return true;
    }
    if (command.getName().equalsIgnoreCase("leave")) {
        doLeave(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 UHPluginCommand> 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.description.JavaServiceDesc.java

/**
 * Makes sure we have completely synchronized OperationDescs with
 * the implementation class.//from   w  w  w  .  ja v  a2 s .c  o  m
 */
private void getSyncedOperationsForName(Class implClass, String methodName) {
    // If we're a Skeleton deployment, skip the statics.
    if (isSkeletonClass) {
        if (methodName.equals("getOperationDescByName") || methodName.equals("getOperationDescs"))
            return;
    }

    // If we have no implementation class, don't worry about it (we're
    // probably on the client)
    if (implClass == null)
        return;

    // If we're done introspecting, or have completed this method, return
    if (completedNames == null || completedNames.contains(methodName))
        return;

    // Skip it if it's not a sanctioned method name
    if ((allowedMethods != null) && !allowedMethods.contains(methodName))
        return;

    if ((disallowedMethods != null) && disallowedMethods.contains(methodName))
        return;

    // If we're a skeleton class, make sure we don't already have any
    // OperationDescs for this name (as that might cause conflicts),
    // then load them up from the Skeleton class.
    if (isSkeletonClass && !haveAllSkeletonMethods) {
        // FIXME : Check for existing ones and fault if found

        if (skelMethod == null) {
            // Grab metadata from the Skeleton for parameter info
            try {
                skelMethod = implClass.getDeclaredMethod("getOperationDescByName",
                        new Class[] { String.class });
            } catch (NoSuchMethodException e) {
            } catch (SecurityException e) {
            }
            if (skelMethod == null) {
                // FIXME : Throw an error?
                return;
            }
        }
        try {
            List skelList = (List) skelMethod.invoke(implClass, new Object[] { methodName });
            if (skelList != null) {
                Iterator i = skelList.iterator();
                while (i.hasNext()) {
                    addOperationDesc((OperationDesc) i.next());
                }
            }
        } catch (IllegalAccessException e) {
            if (log.isDebugEnabled()) {
                log.debug(Messages.getMessage("exception00"), e);
            }
            return;
        } catch (IllegalArgumentException e) {
            if (log.isDebugEnabled()) {
                log.debug(Messages.getMessage("exception00"), e);
            }
            return;
        } catch (InvocationTargetException e) {
            if (log.isDebugEnabled()) {
                log.debug(Messages.getMessage("exception00"), e);
            }
            return;
        }
    }

    // OK, go find any current OperationDescs for this method name and
    // make sure they're synced with the actual class.
    if (name2OperationsMap != null) {
        ArrayList currentOverloads = (ArrayList) name2OperationsMap.get(methodName);
        if (currentOverloads != null) {
            // For each one, sync it to the implementation class' methods
            for (Iterator i = currentOverloads.iterator(); i.hasNext();) {
                OperationDesc oper = (OperationDesc) i.next();
                if (oper.getMethod() == null) {
                    syncOperationToClass(oper, implClass);
                }
            }
        }
    }

    // Now all OperationDescs from deployment data have been completely
    // filled in.  So we now make new OperationDescs for any method
    // overloads which were not covered above.
    // NOTE : This is the "lenient" approach, which allows you to
    // specify one overload and still get the others by introspection.
    // We could equally well return above if we found OperationDescs,
    // and have a rule that if you specify any overloads, you must specify
    // all the ones you want accessible.

    createOperationsForName(implClass, methodName);

    // Note that we never have to look at this method name again.
    completedNames.add(methodName);
}