Example usage for java.lang NoSuchMethodException NoSuchMethodException

List of usage examples for java.lang NoSuchMethodException NoSuchMethodException

Introduction

In this page you can find the example usage for java.lang NoSuchMethodException NoSuchMethodException.

Prototype

public NoSuchMethodException(String s) 

Source Link

Document

Constructs a NoSuchMethodException with a detail message.

Usage

From source file:eu.qualityontime.commons.QPropertyUtilsBean.java

public Object _getIndexedProperty(final Object bean, final String name, final int index) throws Exception {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }//w w  w.j a v a 2  s . c  o m
    if (name == null || name.length() == 0) {
        if (bean.getClass().isArray()) {
            return Array.get(bean, index);
        } else if (bean instanceof List) {
            return ((List<?>) bean).get(index);
        }
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" + bean.getClass() + "'");
    }

    if (name.startsWith("@")) {
        Object f = FieldUtils.readField(bean, trimAnnotations(name));
        if (null == f) {
            if (name.endsWith("?"))
                return null;
            else
                throw new NestedNullException();
        }
        if (f.getClass().isArray())
            return Array.get(f, index);
        else if (f instanceof List)
            return ((List<?>) f).get(index);
    }
    // Retrieve the property descriptor for the specified property
    final PropertyDescriptor descriptor = getPropertyDescriptor(bean, trimAnnotations(name));
    if (descriptor == null) {
        throw new NoSuchMethodException(
                "Unknown property '" + name + "' on bean class '" + bean.getClass() + "'");
    }

    // Call the indexed getter method if there is one
    if (descriptor instanceof IndexedPropertyDescriptor) {
        Method readMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedReadMethod();
        readMethod = MethodUtils.getAccessibleMethod(bean.getClass(), readMethod);
        if (readMethod != null) {
            final Object[] subscript = new Object[1];
            subscript[0] = new Integer(index);
            try {
                return invokeMethod(readMethod, bean, subscript);
            } catch (final InvocationTargetException e) {
                if (e.getTargetException() instanceof IndexOutOfBoundsException) {
                    throw (IndexOutOfBoundsException) e.getTargetException();
                } else {
                    throw e;
                }
            }
        }
    }

    // Otherwise, the underlying property must be an array
    final Method readMethod = getReadMethod(bean.getClass(), descriptor);
    if (readMethod == null) {
        throw new NoSuchMethodException(
                "Property '" + name + "' has no " + "getter method on bean class '" + bean.getClass() + "'");
    }

    // Call the property getter and return the value
    final Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY);
    if (null == value && name.endsWith("?"))
        return null;
    if (!value.getClass().isArray()) {
        if (!(value instanceof java.util.List)) {
            throw new IllegalArgumentException(
                    "Property '" + name + "' is not indexed on bean class '" + bean.getClass() + "'");
        } else {
            // get the List's value
            return ((java.util.List<?>) value).get(index);
        }
    } else {
        // get the array's value
        try {
            return Array.get(value, index);
        } catch (final ArrayIndexOutOfBoundsException e) {
            throw new ArrayIndexOutOfBoundsException(
                    "Index: " + index + ", Size: " + Array.getLength(value) + " for property '" + name + "'");
        }
    }

}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

private static BlockAdder createBlockAdder() throws NoSuchMethodException {
    for (Method method : ClientProtocol.class.getMethods()) {
        if (method.getName().equals("addBlock")) {
            final Method addBlockMethod = method;
            Class<?>[] paramTypes = addBlockMethod.getParameterTypes();
            if (paramTypes[paramTypes.length - 1] == String[].class) {
                return new BlockAdder() {

                    @Override//from   www.  ja v a2 s  .  co m
                    public LocatedBlock addBlock(ClientProtocol namenode, String src, String clientName,
                            ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
                            String[] favoredNodes) throws IOException {
                        try {
                            return (LocatedBlock) addBlockMethod.invoke(namenode, src, clientName, previous,
                                    excludeNodes, fileId, favoredNodes);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        } catch (InvocationTargetException e) {
                            Throwables.propagateIfPossible(e.getTargetException(), IOException.class);
                            throw new RuntimeException(e);
                        }
                    }
                };
            } else {
                return new BlockAdder() {

                    @Override
                    public LocatedBlock addBlock(ClientProtocol namenode, String src, String clientName,
                            ExtendedBlock previous, DatanodeInfo[] excludeNodes, long fileId,
                            String[] favoredNodes) throws IOException {
                        try {
                            return (LocatedBlock) addBlockMethod.invoke(namenode, src, clientName, previous,
                                    excludeNodes, fileId, favoredNodes, null);
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        } catch (InvocationTargetException e) {
                            Throwables.propagateIfPossible(e.getTargetException(), IOException.class);
                            throw new RuntimeException(e);
                        }
                    }
                };
            }
        }
    }
    throw new NoSuchMethodException("Can not find addBlock method in ClientProtocol");
}

From source file:com.gdevelop.gwt.syncrpc.SyncClientSerializationStreamReader.java

private void deserializeWithCustomFieldDeserializer(Class<?> customSerializer, Class<?> instanceClass,
        Object instance) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    assert (!instanceClass.isArray());

    for (Method method : customSerializer.getMethods()) {
        if ("deserialize".equals(method.getName())) {
            method.invoke(null, this, instance);
            return;
        }//from w  ww .j  a  v  a  2 s  .  c  o m
    }
    throw new NoSuchMethodException("deserialize");
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>//from w  w w  .ja  va 2 s  . com
 * Invoke a named static method whose parameter type matches the object
 * type.
 * </p>
 *
 * <p>
 * The behaviour of this method is less deterministic than
 * {@link #invokeExactStaticMethod(Class objectClass,String methodName,Object [] args,Class[] parameterTypes)}.
 * It loops through all methods with names that match and then executes the
 * first it finds with compatible parameters.
 * </p>
 *
 * <p>
 * This method supports calls to methods taking primitive parameters via
 * passing in wrapping classes. So, for example, a <code>Boolean</code>
 * class would match a <code>boolean</code> primitive.
 * </p>
 *
 *
 * @param objectClass
 *            invoke static method on this class
 * @param methodName
 *            get method with this name
 * @param args
 *            use these arguments - treat null as empty array (passing null
 *            will result in calling the parameterless method with name
 *            {@code methodName}).
 * @param parameterTypes
 *            match these parameters - treat null as empty array
 * @return The value returned by the invoked method
 *
 * @throws NoSuchMethodException
 *             if there is no such accessible method
 * @throws InvocationTargetException
 *             wraps an exception thrown by the method invoked
 * @throws IllegalAccessException
 *             if the requested method is not accessible via reflection
 * @since 1.8.0
 */
public static Object invokeStaticMethod(final Class<?> objectClass, final String methodName, Object[] args,
        Class<?>[] parameterTypes)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {

    if (parameterTypes == null) {
        parameterTypes = EMPTY_CLASS_PARAMETERS;
    }
    if (args == null) {
        args = EMPTY_OBJECT_ARRAY;
    }

    final Method method = getMatchingAccessibleMethod(objectClass, methodName, parameterTypes);
    if (method == null) {
        throw new NoSuchMethodException(
                "No such accessible method: " + methodName + "() on class: " + objectClass.getName());
    }
    return method.invoke(null, args);
}

From source file:org.apache.hadoop.hbase.io.asyncfs.FanOutOneBlockAsyncDFSOutputHelper.java

private static ChecksumCreater createChecksumCreater28(Class<?> confClass) throws NoSuchMethodException {
    for (Method method : confClass.getMethods()) {
        if (method.getName().equals("createChecksum")) {
            final Method createChecksumMethod = method;
            return new ChecksumCreater() {

                @Override// ww w.  j av  a 2s .c  om
                public DataChecksum createChecksum(Object conf) {
                    try {
                        return (DataChecksum) createChecksumMethod.invoke(conf, (Object) null);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        throw new RuntimeException(e);
                    }
                }
            };
        }
    }
    throw new NoSuchMethodException("Can not find createChecksum method in DfsClientConf");
}

From source file:com.p5solutions.core.jpa.orm.EntityUtility.java

/**
 * Builds the the Parameter Binder list starting from a class, not necessarily
 * the root class.//w w  w. ja v  a 2s .c om
 * 
 * @param <T>
 *          the generic type
 * @param entityClass
 *          the clazz
 * @param bindingPath
 *          the binding path
 * @param parentClass
 *          the parent class, <code>null</code> if root class
 * @param parentGetterMethod
 *          the parent getter method, <code>null</code> if root class
 * @param parentSetterMethod
 *          the parent setter method, <code>null</code> if root class
 * @param pbs
 *          the pbs
 * @param recursionFilterList
 *          the recursion filter list
 */
public <T> void build(Class<T> entityClass, String bindingPath, Class<?> parentClass, Method parentGetterMethod,
        Method parentSetterMethod, List<ParameterBinder> pbs, List<Class<?>> recursionFilterList) {

    List<Method> methods = ReflectionUtility.findGetMethodsWithNoParams(entityClass);

    // if the methods are blank or null then throw an exception, cannot be
    // an empty entity type
    if (Comparison.isEmptyOrNull(methods)) {
        String error = "No getters found for entity/embedded class type " + entityClass
                + " which represent a column property; make sure "
                + "the getters do no have any accepting parameters; such as getSomeField(...) { }";
        logger.error(error);
        throw new NullPointerException(error);
    }

    int index = 1; // the parameter binding index in a Sql Parameter

    // //
    for (Method getterMethod : methods) {
        // @Transient methods are not to be used for binding
        if (ReflectionUtility.isTransient(getterMethod)) {
            continue;
        }
        // look up the setter method (must exist for non-transient getters)
        Method setterMethod = ReflectionUtility.findSetterMethod(entityClass, getterMethod);
        if (setterMethod == null) {
            String error = "No related 'set' method found for 'get' method " + getterMethod.getName()
                    + " when processing entity type " + entityClass;
            logger.fatal(error);
            throw new RuntimeException(new NoSuchMethodException(error));
        }

        // attempt to build the embeddable, if any, if not returns
        // false, and continues with default parameter builder
        if (!buildEmbeddable(entityClass, bindingPath, getterMethod, setterMethod, pbs, recursionFilterList)) {

            // default non embedded params
            ParameterBinder pb = buildParameterBinder(entityClass, bindingPath, getterMethod, setterMethod,
                    parentGetterMethod, parentSetterMethod, index++, recursionFilterList);

            // MOVED TO buildParamaterBinder
            // // set the binding path if any.
            // String fieldName = ReflectionUtility.buildFieldName(getterMethod);
            // if (parentGetterMethod != null) {
            // pb.setBindingPath(bindingPath + "." + fieldName);
            // } else {
            // pb.setBindingPath(fieldName);
            // }

            // this may not be null, such as embedded objects, the parent
            // methods should be available.
            pb.setEntityClass(entityClass); // probably redundant, since its done
            // in buildParamterBinder(...)
            pb.setParentClass(parentClass);
            pb.setParentGetterMethod(parentGetterMethod);
            pb.setParentSetterMethod(parentSetterMethod);

            // add the parameter to the list of all parameters
            pbs.add(pb);
        }
    }
}

From source file:com.hc.wx.server.common.bytecode.ReflectUtils.java

/**
 * ???/*from w  ww. j a  v a 2s  . c  o m*/
 * 
 * @param clazz 
 * @param methodName ??method1(int, String)?????????method2
 * @return 
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException  
 * @throws IllegalStateException ???????
 */
public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes)
        throws NoSuchMethodException, ClassNotFoundException {
    String signature = clazz.getName() + "." + methodName;
    if (parameterTypes != null && parameterTypes.length > 0) {
        signature += StringUtils.join(parameterTypes);
    }
    Method method = Signature_METHODS_CACHE.get(signature);
    if (method != null) {
        return method;
    }
    if (parameterTypes == null) {
        List<Method> finded = new ArrayList<Method>();
        for (Method m : clazz.getMethods()) {
            if (m.getName().equals(methodName)) {
                finded.add(m);
            }
        }
        if (finded.isEmpty()) {
            throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
        }
        if (finded.size() > 1) {
            String msg = String.format("Not unique method for method name(%s) in class(%s), find %d methods.",
                    methodName, clazz.getName(), finded.size());
            throw new IllegalStateException(msg);
        }
        method = finded.get(0);
    } else {
        Class<?>[] types = new Class<?>[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            types[i] = ReflectUtils.name2class(parameterTypes[i]);
        }
        method = clazz.getMethod(methodName, types);

    }
    Signature_METHODS_CACHE.put(signature, method);
    return method;
}

From source file:shared.utils.ReflectUtils.java

/**
 * ???/*from  ww w. j a va2 s  .  com*/
 *
 * @param clazz 
 * @param methodName ??method1(int, String)?????????method2
 * @param parameterLength ???methodName??????
 * @return 
 * @throws NoSuchMethodException
 * @throws ClassNotFoundException
 * @throws IllegalStateException ???????
 */
public static Method findMethodByMethodSignature(Class<?> clazz, String methodName, String[] parameterTypes,
        int parameterLength) throws NoSuchMethodException, ClassNotFoundException {
    String signature = clazz.getName() + "." + methodName;
    if (parameterTypes != null && parameterTypes.length > 0) {
        signature = signature + StringUtils.join(parameterTypes);
    }
    Method method = Signature_METHODS_CACHE.get(signature);
    if (method != null) {
        return method;
    }
    if (parameterTypes == null) {
        List<Method> finded = new ArrayList<Method>();
        for (Method m : clazz.getMethods()) {
            if (m.getName().equals(methodName)) {
                finded.add(m);
            }
        }
        if (finded.isEmpty()) {
            throw new NoSuchMethodException("No such method " + methodName + " in class " + clazz);
        }
        if (finded.size() > 1) {
            int sameParameterLengthMethodCount = 0;
            for (Method fm : finded) {
                if (fm.getParameterTypes().length == parameterLength) {
                    sameParameterLengthMethodCount++;
                    method = fm;
                }
            }

            if (sameParameterLengthMethodCount == 0) {
                String msg = String.format(
                        "Not matching method for method name(%s) in class(%s), expected parameter length %d.",
                        methodName, clazz.getName(), parameterLength);
                throw new IllegalStateException(msg);
            } else if (sameParameterLengthMethodCount == 1) {
                //??
                return method;
            } else {
                String msg = String.format(
                        "Not unique method for method name(%s) in class(%s), find %d methods, expected parameter length %d.",
                        methodName, clazz.getName(), finded.size(), parameterLength);
                throw new IllegalStateException(msg);
            }
        }
        method = finded.get(0);
    } else {
        Class<?>[] types = new Class<?>[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            types[i] = ReflectUtils.name2class(parameterTypes[i]);
        }
        method = clazz.getMethod(methodName, types);

    }
    Signature_METHODS_CACHE.put(signature, method);
    return method;
}

From source file:org.jabsorb.ng.JSONRPCBridge.java

/**
 * Call a method using a JSON-RPC request object.
 * //from  ww w  .ja v  a  2  s  .  c o m
 * @param context
 *            The transport context (the HttpServletRequest and
 *            HttpServletResponse objects in the case of the HTTP
 *            transport).
 * 
 * @param jsonReq
 *            The JSON-RPC request structured as a JSON object tree.
 * 
 * @return a JSONRPCResult object with the result of the invocation or an
 *         error.
 */
public JSONRPCResult call(final Object context[], final JSONObject jsonReq) {

    // #1: Parse the request
    final String encodedMethod;
    final Object requestId;
    JSONArray arguments;
    final JSONArray fixups;
    try {
        encodedMethod = jsonReq.getString("method");
        arguments = jsonReq.optJSONArray("params");
        requestId = jsonReq.opt("id");
        fixups = jsonReq.optJSONArray("fixups");

        if (arguments == null) {
            // T. Calmant: Use an empty array if necessary
            arguments = new JSONArray();
        }

    } catch (final JSONException e) {
        log.error("call", "no method or parameters in request");
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD);
    }
    if (log.isDebugEnabled()) {
        if (fixups != null) {
            log.debug("call", "call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId);
        } else {
            log.debug("call", "call " + encodedMethod + "(" + arguments + ")" + ", fixups=" + fixups
                    + ", requestId=" + requestId);
        }
    }

    // apply the fixups (if any) to the parameters. This will result
    // in a JSONArray that might have circular references-- so
    // the toString method (or anything that internally tries to traverse
    // the JSON (without being aware of this) should not be called after
    // this
    // point

    if (fixups != null) {
        try {
            for (int i = 0; i < fixups.length(); i++) {
                final JSONArray assignment = fixups.getJSONArray(i);
                final JSONArray fixup = assignment.getJSONArray(0);
                final JSONArray original = assignment.getJSONArray(1);
                applyFixup(arguments, fixup, original);
            }
        } catch (final JSONException e) {
            log.error("call", "error applying fixups", e);

            return new JSONRPCResult(JSONRPCResult.CODE_ERR_FIXUP, requestId,
                    JSONRPCResult.MSG_ERR_FIXUP + ": " + e.getMessage());
        }
    }

    // #2: Get the name of the class and method from the encodedMethod
    final String className;
    final String methodName;
    {
        final StringTokenizer t = new StringTokenizer(encodedMethod, ".");
        if (t.hasMoreElements()) {
            className = t.nextToken();
        } else {
            className = null;
        }
        if (t.hasMoreElements()) {
            methodName = t.nextToken();
        } else {
            methodName = null;
        }
    }

    // #3: Get the id of the object (if it exists) from the className
    // (in the format: ".obj#<objectID>")
    final int objectID;
    {
        final int objectStartIndex = encodedMethod.indexOf('[');
        final int objectEndIndex = encodedMethod.indexOf(']');
        if (encodedMethod.startsWith(OBJECT_METHOD_PREFIX) && (objectStartIndex != -1) && (objectEndIndex != -1)
                && (objectStartIndex < objectEndIndex)) {
            objectID = Integer.parseInt(encodedMethod.substring(objectStartIndex + 1, objectEndIndex));
        } else {
            objectID = 0;
        }
    }
    // #4: Handle list method calls
    if ((objectID == 0) && (encodedMethod.equals("system.listMethods"))) {
        return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, systemListMethods());
    }

    // #5: Get the object to act upon and the possible method that could be
    // called on it
    final Map<AccessibleObjectKey, List<? extends AccessibleObject>> methodMap;
    final Object javascriptObject;
    final AccessibleObject ao;
    try {
        javascriptObject = getObjectContext(objectID, className);
        methodMap = getAccessibleObjectMap(objectID, className, methodName);
        // #6: Resolve the method
        ao = AccessibleObjectResolver.resolveMethod(methodMap, methodName, arguments, ser);
        if (ao == null) {
            throw new NoSuchMethodException(JSONRPCResult.MSG_ERR_NOMETHOD);
        }
    } catch (final NoSuchMethodException e) {
        if (e.getMessage().equals(JSONRPCResult.MSG_ERR_NOCONSTRUCTOR)) {
            return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOCONSTRUCTOR, requestId,
                    JSONRPCResult.MSG_ERR_NOCONSTRUCTOR);
        }
        return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId, JSONRPCResult.MSG_ERR_NOMETHOD);
    }

    // #7: Call the method
    final JSONRPCResult r = AccessibleObjectResolver.invokeAccessibleObject(ao, context, arguments,
            javascriptObject, requestId, ser, cbc, exceptionTransformer);
    return r;
}

From source file:org.kuali.rice.kns.web.struts.form.pojo.PojoPropertyUtilsBean.java

/**
 * Set the value of the specified simple property of the specified bean,
 * with no type conversions./*from   w  w w  . ja  va  2 s.  co m*/
 *
 * @param bean Bean whose property is to be modified
 * @param name Name of the property to be modified
 * @param value Value to which the property should be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception IllegalArgumentException if <code>bean</code> or
 *  <code>name</code> is null
 * @exception IllegalArgumentException if the property name is
 *  nested or indexed
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 * @exception NoSuchMethodException if an accessor method for this
 *  propety cannot be found
 */
public void setSimpleProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        if (LOG.isDebugEnabled())
            LOG.debug("No bean specified, name = " + name + ", value = " + value);
        return;
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified");
    }

    // Validate the syntax of the property name
    if (name.indexOf(PropertyUtils.NESTED_DELIM) >= 0) {
        throw new IllegalArgumentException("Nested property names are not allowed");
    } else if (name.indexOf(PropertyUtils.INDEXED_DELIM) >= 0) {
        throw new IllegalArgumentException("Indexed property names are not allowed");
    } else if (name.indexOf(PropertyUtils.MAPPED_DELIM) >= 0) {
        throw new IllegalArgumentException("Mapped property names are not allowed");
    }

    // Retrieve the property setter method for the specified property
    PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);
    if (descriptor == null) {
        throw new NoSuchMethodException("Unknown property '" + name + "'");
    }
    Method writeMethod = getWriteMethod(descriptor);
    if (writeMethod == null) {
        //throw new NoSuchMethodException("Property '" + name + "' has no setter method");
        LOG.warn("Bean: " + bean.getClass().getName() + ", Property '" + name + "' has no setter method");
        return;
    }

    // Call the property setter method
    Object values[] = new Object[1];
    values[0] = value;
    if (LOG.isDebugEnabled()) {
        String valueClassName = value == null ? "<null>" : value.getClass().getName();
        LOG.debug("setSimpleProperty: Invoking method " + writeMethod + " with value " + value + " (class "
                + valueClassName + ")");
    }

    invokeMethod(writeMethod, bean, values);

}