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.example.android.network.sync.basicsyncadapter.SyncAdapter.java

private void deleteAllDeletedRecordsAtServer(SyncResult syncResult) {
    for (Class sClass : modelsRegisteredForSync) {
        try {//from  w ww  . j a v  a2s .  c o m

            Class[] cArg = new Class[1];
            cArg[0] = Context.class;

            Method methodToGetDeletedObjects = sClass.getDeclaredMethod("fetchAllDeletedObjectsInDB", cArg);

            ArrayList<Object> objectsToBeDeleted = (ArrayList<Object>) methodToGetDeletedObjects.invoke(null,
                    getContext());

            for (Object obj : objectsToBeDeleted) {
                deleteObjectAtServerForObject(obj, syncResult);
            }

        }

        catch (Exception ex) {
            System.out.println(ex.toString());
        }

    }

    syncCompleted();
}

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

private void postAllNewlyCreatedRecordsToServer(SyncResult syncResult) {
    SyncResult result = syncResult;/*from w w  w . java  2 s .  co  m*/

    for (Class sClass : modelsRegisteredForSync) {
        try {

            Class[] cArg = new Class[1];
            cArg[0] = Context.class;

            Method methodForNewlyCreatedObjects = sClass.getDeclaredMethod("fetchAllNewObjectsInDB", cArg);

            ArrayList<Object> objectsToBeCreated = (ArrayList<Object>) methodForNewlyCreatedObjects.invoke(null,
                    getContext());

            for (Object obj : objectsToBeCreated) {
                createNewObjectAtServerForObject(obj, syncResult);
            }

        }

        catch (Exception ex) {
            System.out.println(ex.toString());
        }

    }

    deleteAllDeletedRecordsAtServer(result);
}

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

private void postAllDirtyRecordsToServer(SyncResult syncResult) {
    SyncResult result = syncResult;/*from  w  w  w  .ja  va  2 s .c  om*/

    for (Class sClass : modelsRegisteredForSync) {
        try {

            Class[] cArg = new Class[1];
            cArg[0] = Context.class;

            Method methodForGettingDirtyObjects = sClass.getDeclaredMethod("fetchAllDirtyObjectsInDB", cArg);

            ArrayList<Object> objectsToBeUpdated = (ArrayList<Object>) methodForGettingDirtyObjects.invoke(null,
                    getContext());

            for (Object obj : objectsToBeUpdated) {
                updateObjectAtServerForObject(obj, syncResult);
            }

        }

        catch (Exception ex) {
            System.out.println(ex.toString());
        }

    }

    postAllNewlyCreatedRecordsToServer(result);

}

From source file:net.chaosserver.timelord.swingui.CommonTaskPanel.java

/**
 * Hides the application window out of site and mind on Win and Mac.
 *//*w w w  .  j  ava 2s .c  o  m*/
protected void hideFrame() {
    JFrame frame = (JFrame) SwingUtilities.getAncestorOfClass(JFrame.class, this);
    frame.toBack();

    // Use reflection for compile-time avoidance.
    try {
        Class<?> nsApplicationClass = Class.forName("com.apple.cocoa.application.NSApplication");
        Method sharedAppMethod = nsApplicationClass.getDeclaredMethod("sharedApplication", new Class<?>[] {});

        Object nsApplicationObject = sharedAppMethod.invoke(null, new Object[] {});

        /*
        Field userAttentionRequestCriticalField =
        nsApplicationClass.getDeclaredField(
            "UserAttentionRequestCritical");
        */

        Method hideMethod = nsApplicationClass.getDeclaredMethod("hide", new Class[] { Object.class });

        hideMethod.invoke(nsApplicationObject, new Object[] { nsApplicationObject });
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Issue bouncing dock", e);
        }
    }
}

From source file:com.snaplogic.snaps.uniteller.BaseService.java

@Override
protected void process(Document document, String inputViewName) {
    try {/*from w  w  w  . j a va2  s  .  c  o  m*/
        AccountBean bean = account.connect();
        String UFSConfigFilePath = urlEncoder.validateAndEncodeURI(bean.getConfigFilePath(), PATTERN, null)
                .toString();
        String UFSSecurityFilePath = urlEncoder
                .validateAndEncodeURI(bean.getSecurityPermFilePath(), PATTERN, null).toString();
        /* instantiating USFCreationClient */
        Class<?> CustomUSFCreationClient = Class.forName(UFS_FOLIO_CREATION_CLIENT_PKG_URI);
        Constructor<?> constructor = CustomUSFCreationClient
                .getDeclaredConstructor(new Class[] { IUFSConfigMgr.class, IUFSSecurityMgr.class });
        Object USFCreationClientObj = constructor.newInstance(CustomUFSConfigMgr.getInstance(UFSConfigFilePath),
                CustomUFSSecurityMgr.getInstance(UFSSecurityFilePath));
        Method setAutoUpdatePsw = CustomUSFCreationClient.getDeclaredMethod("setAutoUpdatePsw", Boolean.TYPE);
        setAutoUpdatePsw.invoke(USFCreationClientObj, autoUpdatePsw);
        /* Preparing the request for USF */
        Object data;
        if (document != null && (data = document.get()) != null) {
            if (data instanceof Map) {
                Map<String, Object> map = (Map<String, Object>) data;
                Class<?> UFSRequest = Class.forName(getUFSReqClassType());
                Object UFSRequestObj = UFSRequest.newInstance();
                Object inputFieldValue = null;
                Calendar cal = Calendar.getInstance();
                for (Method method : UFSRequest.getDeclaredMethods()) {
                    if (isSetter(method)
                            && (inputFieldValue = map.get(method.getName().substring(3))) != null) {
                        try {
                            String paramType = method.getParameterTypes()[0].getName();
                            if (paramType.equalsIgnoreCase(String.class.getName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj), String.valueOf(inputFieldValue));
                            } else if (paramType.equalsIgnoreCase(Double.class.getSimpleName())) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Double.parseDouble(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(INT)) {
                                method.invoke(UFSRequest.cast(UFSRequestObj),
                                        Integer.parseInt(String.valueOf(inputFieldValue)));
                            } else if (paramType.equalsIgnoreCase(Calendar.class.getName())) {
                                try {
                                    cal.setTime(sdtf.parse(String.valueOf(inputFieldValue)));
                                } catch (ParseException pe1) {
                                    try {
                                        cal.setTime(sdf.parse(String.valueOf(inputFieldValue)));
                                    } catch (ParseException pe) {
                                        writeToErrorView(
                                                String.format(DATE_PARSER_ERROR, DATETIME_FORMAT, DATE_FORMAT),
                                                pe.getMessage(), ERROR_RESOLUTION, pe);
                                    }
                                }
                                method.invoke(UFSRequest.cast(UFSRequestObj), cal);
                            }
                        } catch (IllegalArgumentException iae) {
                            writeToErrorView(String.format(ILLEGAL_ARGS_EXE, method.getName()),
                                    iae.getMessage(), ERROR_RESOLUTION, iae);
                        } catch (InvocationTargetException ite) {
                            writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(),
                                    ERROR_RESOLUTION, ite);
                        }
                    }
                }
                /* Invoking the request over USFCreationClient */
                Object UFSResponseObj = null;
                Method creationClientMethod = CustomUSFCreationClient
                        .getMethod(getCamelCaseForMethod(resourceType), UFSRequest);
                try {
                    UFSResponseObj = creationClientMethod.invoke(USFCreationClientObj,
                            UFSRequest.cast(UFSRequestObj));
                } catch (IllegalArgumentException iae) {
                    writeToErrorView(String.format(ILLEGAL_ARGS_EXE, creationClientMethod.getName()),
                            iae.getMessage(), ERROR_RESOLUTION, iae);
                } catch (InvocationTargetException ite) {
                    writeToErrorView(ite.getTargetException().getMessage(), ite.getMessage(), ERROR_RESOLUTION,
                            ite);
                }
                if (null != UFSResponseObj) {
                    outputViews.write(documentUtility.newDocument(processResponseObj(UFSResponseObj)));
                    counter.inc();
                }
            } else {
                writeToErrorView(NO_DATA_ERRMSG, NO_DATA_WARNING, NO_DATA_REASON, NO_DATA_RESOLUTION);
            }
        }
    } catch (Exception ex) {
        writeToErrorView(ERRORMSG, ex.getMessage(), ERROR_RESOLUTION, ex);
    }
}

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

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

    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);
                    setMethod.invoke(instance, convertValue(type, value));
                    break;
                } catch (NoSuchMethodException ex) {
                    klass = klass.getSuperclass();
                }
            }
        }
    }
}

From source file:net.sourceforge.cobertura.reporting.ComplexityCalculator.java

/**
 * Computes CCN for a method./* w  w w.  j a  v a2 s  .c  o  m*/
 *
 * @param classData        class data for the class which contains the method to compute CCN for
 * @param methodName       the name of the method to compute CCN for
 * @param methodDescriptor the descriptor of the method to compute CCN for
 * @return CCN for the method
 * @throws NullPointerException if <code>classData</code> is <code>null</code>
 */
public int getCCNForMethod(ClassData classData, String methodName, String methodDescriptor) {
    if (!calculateMethodComplexity) {
        return 0;
    }

    Validate.notNull(classData, "classData must not be null");
    Validate.notNull(methodName, "methodName must not be null");
    Validate.notNull(methodDescriptor, "methodDescriptor must not be null");

    int complexity = 0;
    List<FunctionMetric> methodMetrics = getFunctionMetricsForSingleFile(classData.getSourceFileName());

    // golden method = method for which we need ccn
    String goldenMethodName = methodName;
    boolean isConstructor = false;
    if (goldenMethodName.equals("<init>")) {
        isConstructor = true;
        goldenMethodName = classData.getBaseName();
    }
    // fully-qualify the method
    goldenMethodName = classData.getName() + "." + goldenMethodName;
    // replace nested class separator $ by .
    goldenMethodName = goldenMethodName.replaceAll(Pattern.quote("$"), ".");

    TraceSignatureVisitor v = new TraceSignatureVisitor(Opcodes.ACC_PUBLIC);
    SignatureReader r = new SignatureReader(methodDescriptor);
    r.accept(v);

    // for the scope of this method, signature = signature of the method excluding the method name
    String goldenSignature = v.getDeclaration();
    // get parameter type list string which is enclosed by round brackets ()
    goldenSignature = goldenSignature.substring(1, goldenSignature.length() - 1);

    // collect all the signatures with the same method name as golden method
    Map<String, Integer> candidateSignatureToCcn = new HashMap<String, Integer>();
    for (FunctionMetric singleMethodMetrics : methodMetrics) {
        String candidateMethodName = singleMethodMetrics.name.substring(0,
                singleMethodMetrics.name.indexOf('('));
        String candidateSignature = stripTypeParameters(singleMethodMetrics.name
                .substring(singleMethodMetrics.name.indexOf('(') + 1, singleMethodMetrics.name.length() - 1));
        if (goldenMethodName.equals(candidateMethodName)) {
            candidateSignatureToCcn.put(candidateSignature, singleMethodMetrics.ccn);
        }
    }

    // if only one signature, no signature matching needed
    if (candidateSignatureToCcn.size() == 1) {
        return candidateSignatureToCcn.values().iterator().next();
    }

    // else, do signature matching and find the best match

    // update golden signature using reflection
    if (!goldenSignature.isEmpty()) {
        try {
            String[] goldenParameterTypeStrings = goldenSignature.split(",");
            Class<?>[] goldenParameterTypes = new Class[goldenParameterTypeStrings.length];
            for (int i = 0; i < goldenParameterTypeStrings.length; i++) {
                goldenParameterTypes[i] = ClassUtils.getClass(goldenParameterTypeStrings[i].trim(), false);
            }
            Class<?> klass = ClassUtils.getClass(classData.getName(), false);
            if (isConstructor) {
                Constructor<?> realMethod = klass.getDeclaredConstructor(goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            } else {
                Method realMethod = klass.getDeclaredMethod(methodName, goldenParameterTypes);
                goldenSignature = realMethod.toGenericString();
            }
            // replace varargs ellipsis with array notation
            goldenSignature = goldenSignature.replaceAll("\\.\\.\\.", "[]");
            // extract the parameter type list string
            goldenSignature = goldenSignature.substring(goldenSignature.indexOf("(") + 1,
                    goldenSignature.length() - 1);
            // strip the type parameters to get raw types
            goldenSignature = stripTypeParameters(goldenSignature);
        } catch (Exception e) {
            logger.error("Error while getting method CC for " + goldenMethodName, e);
            return 0;
        }
    }
    // replace nested class separator $ by .
    goldenSignature = goldenSignature.replaceAll(Pattern.quote("$"), ".");

    // signature matching - due to loss of fully qualified parameter types from JavaCC, get ccn for the closest match
    double signatureMatchPercentTillNow = 0;
    for (Entry<String, Integer> candidateSignatureToCcnEntry : candidateSignatureToCcn.entrySet()) {
        String candidateSignature = candidateSignatureToCcnEntry.getKey();
        double currentMatchPercent = matchSignatures(candidateSignature, goldenSignature);
        if (currentMatchPercent == 1) {
            return candidateSignatureToCcnEntry.getValue();
        }
        if (currentMatchPercent > signatureMatchPercentTillNow) {
            complexity = candidateSignatureToCcnEntry.getValue();
            signatureMatchPercentTillNow = currentMatchPercent;
        }
    }

    return complexity;
}

From source file:org.apache.hadoop.hbase.filter.ParseFilter.java

/**
 * Constructs a filter object given a simple filter expression
 * <p>/*from   w w  w  .  j  a va2s .  c o  m*/
 * @param filterStringAsByteArray filter string given by the user
 * @return filter object we constructed
 */
public Filter parseSimpleFilterExpression(byte[] filterStringAsByteArray) throws CharacterCodingException {

    String filterName = Bytes.toString(getFilterName(filterStringAsByteArray));
    ArrayList<byte[]> filterArguments = getFilterArguments(filterStringAsByteArray);
    if (!filterHashMap.containsKey(filterName)) {
        throw new IllegalArgumentException("Filter Name " + filterName + " not supported");
    }
    try {
        filterName = filterHashMap.get(filterName);
        Class<?> c = Class.forName(filterName);
        Class<?>[] argTypes = new Class[] { ArrayList.class };
        Method m = c.getDeclaredMethod("createFilterFromArguments", argTypes);
        return (Filter) m.invoke(null, filterArguments);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }
    throw new IllegalArgumentException("Incorrect filter string " + new String(filterStringAsByteArray));
}

From source file:lucee.runtime.net.rpc.server.RPCServer.java

private boolean doGet(HttpServletRequest request, HttpServletResponse response, PrintWriter writer,
        Component component) throws AxisFault, ClassException, SecurityException, NoSuchMethodException,
        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

    String path = request.getServletPath();
    String queryString = request.getQueryString();

    AxisEngine engine = getEngine();/* w  ww  .  ja v a  2  s.  com*/

    Iterator i = this.transport.getOptions().keySet().iterator();

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

    String servletURI = request.getContextPath() + path;
    String reqURI = request.getRequestURI();

    // service name
    String serviceName;
    if (servletURI.length() + 1 < reqURI.length()) {
        serviceName = reqURI.substring(servletURI.length() + 1);
    } else {
        serviceName = "";
    }

    while (i.hasNext()) {
        String queryHandler = (String) i.next();
        if (queryHandler.startsWith("qs.")) {
            // Only attempt to match the query string with transport
            // parameters prefixed with "qs:".

            String handlerName = queryHandler.substring(queryHandler.indexOf(".") + 1).toLowerCase();
            // Determine the name of the plugin to invoke by using all text
            // in the query string up to the first occurence of &, =, or the
            // whole string if neither is present.

            int length = 0;
            boolean firstParamFound = false;

            while (firstParamFound == false && length < queryString.length()) {
                char ch = queryString.charAt(length++);

                if (ch == '&' || ch == '=') {
                    firstParamFound = true;

                    --length;
                }
            }

            if (length < queryString.length()) {
                queryString = queryString.substring(0, length);
            }

            if (queryString.toLowerCase().equals(handlerName) == true) {
                // Query string matches a defined query string handler name.

                // If the defined class name for this query string handler is blank,
                // just return (the handler is "turned off" in effect).

                if (this.transport.getOption(queryHandler).equals("")) {
                    return false;
                }

                // Attempt to dynamically load the query string handler
                // and its "invoke" method.

                MessageContext msgContext = createMessageContext(engine, request, response, component);
                Class plugin = ClassUtil.loadClass((String) this.transport.getOption(queryHandler));
                Method pluginMethod = plugin.getDeclaredMethod("invoke", new Class[] { msgContext.getClass() });

                msgContext.setProperty(MessageContext.TRANS_URL,
                        HttpUtils.getRequestURL(request).toString().toLowerCase());
                //msgContext.setProperty(MessageContext.TRANS_URL, "http://DefaultNamespace");
                msgContext.setProperty(HTTPConstants.PLUGIN_SERVICE_NAME, serviceName);
                msgContext.setProperty(HTTPConstants.PLUGIN_NAME, handlerName);
                msgContext.setProperty(HTTPConstants.PLUGIN_IS_DEVELOPMENT, Caster.toBoolean(isDevelopment));
                msgContext.setProperty(HTTPConstants.PLUGIN_ENABLE_LIST, Boolean.FALSE);
                msgContext.setProperty(HTTPConstants.PLUGIN_ENGINE, engine);
                msgContext.setProperty(HTTPConstants.PLUGIN_WRITER, writer);
                msgContext.setProperty(HTTPConstants.PLUGIN_LOG, log);
                msgContext.setProperty(HTTPConstants.PLUGIN_EXCEPTION_LOG, exceptionLog);

                // Invoke the plugin.
                pluginMethod.invoke(ClassUtil.loadInstance(plugin), new Object[] { msgContext });
                writer.close();

                return true;

            }
        }
    }

    return false;
}

From source file:com.heliosphere.demeter.base.runner.AbstractRunner.java

/**
 * Determines the parameters' type.// w ww.  j  av a  2s  .  c o  m
 * <hr>
 * @param enumClass Parameter enumeration class to use to determine the parameters' type.
 * @throws ParameterException Thrown in case an error occurred when determining a parameter type.
 */
@SuppressWarnings({ "unchecked", "rawtypes", "nls" })
private final void determineParameterType(final Class enumClass) throws ParameterException {
    Method method;
    String name = null;
    String value = null;

    this.enumParameterClass = enumClass;
    Object o = Enum.valueOf(enumClass, "UNKNOWN");

    try {
        method = enumClass.getDeclaredMethod("fromName", String.class);

        for (IParameterConfiguration parameter : configuration.getContent().getElements()) {
            value = parameter.getName();
            parameter.setType((Enum<? extends IParameterType>) method.invoke(o, value));
            parameter.setEntityType(((IParameterType) parameter.getType()).getEntityType());
            if (parameter.getType() == null) {
                throw new ParameterException("No parameter definition found for: " + value);
            }
        }

        for (IParameterExecution parameter : execution.getContent().getElements()) {
            name = parameter.getName();
            parameter.setType((Enum<? extends IParameterType>) method.invoke(o, name));
            parameter.setEntityType(((IParameterType) parameter.getType()).getEntityType());
            parameter.setStatus(ParameterStatusType.UNPROCESSED);
            parameter.setConfiguration(configuration.getParameter(parameter.getType()));
        }
    } catch (Exception e) {
        throw new ParameterException(
                String.format("Unable to create enumerated value for enumeration: %1s, parameter: %2s",
                        enumClass.getName(), name == null ? value : name));
    }

    checkParameterDefinitionAgainstEnumeration(o.getClass());
}