List of usage examples for java.lang NoSuchMethodException NoSuchMethodException
public NoSuchMethodException(String s)
NoSuchMethodException
with a detail message. From source file:com.link_intersystems.lang.reflect.Class2.java
/** * Returns the declaring method2 object using the same logic as * {@link Class#getDeclaredMethod(String, Class...)}. * * @param name/*from www. j av a 2 s . co m*/ * the name of the method. * @param parameterTypes * the exact parameter types that the declaring method must have. * @return the {@link Method2} that represents the declaring method with the * name and Assert. * @throws NoSuchMethodException * if no method matches the parameters. * @since 1.0.0.0 */ public Method2 getDeclaringMethod2(String name, Class<?>... parameterTypes) throws NoSuchMethodException { Assert.notNull("parameterTypes", parameterTypes); List<Method2> declaredMethods = getDeclaredMethods(); for (Method2 method2 : declaredMethods) { Class<?>[] parameterTypes2 = method2.getParameterTypes(); if (Arrays.equals(parameterTypes, parameterTypes2)) { return method2; } } throw new NoSuchMethodException("No method named " + name + "( )"); }
From source file:com.jk.util.JKObjectUtil.java
/** * Call method./*w w w . j a v a2 s . c om*/ * * @param obj * the obj * @param methodName * the method name * @param includePrivateMehtods * the include private mehtods * @param args * the args * @throws InvocationTargetException * the invocation target exception */ ////////////////////////////////////////////////////////////////////////////////////////////////////////////////// public static void callMethod(final Object obj, final String methodName, final boolean includePrivateMehtods, final Object... args) throws InvocationTargetException { final Class[] intArgsClass = initParamsClasses(args); try { Class<?> current = obj.getClass(); Method method = null; while (current != Object.class) { try { method = current.getDeclaredMethod(methodName, intArgsClass); break; } catch (final NoSuchMethodException ex) { current = current.getSuperclass(); } } if (method == null) { throw new NoSuchMethodException("Mehtod is not found in " + current); } method.setAccessible(true); method.invoke(obj, args); } catch (final InvocationTargetException e) { throw new InvocationTargetException(e.getCause()); } catch (final Exception e) { throw new InvocationTargetException(e); } }
From source file:com.strider.datadefender.DatabaseAnonymizer.java
/** * Calls the anonymization function for the given Column, and returns its * anonymized value./*from w w w .ja v a2s .c om*/ * * @param dbConn * @param row * @param column * @return * @throws NoSuchMethodException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException * @throws InvocationTargetException */ private Object callAnonymizingFunctionWithoutParameters(final Connection dbConn, final Column column) throws SQLException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { final String function = column.getFunction(); if (function == null || function.equals("")) { log.warn("Function is not defined for column [" + column + "]. Moving to the next column."); return ""; } try { final String className = Utils.getClassName(function); final String methodName = Utils.getMethodName(function); final Class<?> clazz = Class.forName(className); final CoreFunctions instance = (CoreFunctions) Class.forName(className).newInstance(); instance.setDatabaseConnection(dbConn); final Method[] methods = clazz.getMethods(); Method selectedMethod = null; Object returnType = null; methodLoop: for (final Method m : methods) { //if (m.getName().equals(methodName) && m.getReturnType() == String.class) { if (m.getName().equals(methodName)) { log.debug(" Found method: " + m.getName()); selectedMethod = m; returnType = m.getReturnType(); break; } } if (selectedMethod == null) { final StringBuilder s = new StringBuilder("Anonymization method: "); s.append(methodName).append(") was not found in class ").append(className); throw new NoSuchMethodException(s.toString()); } log.debug("Anonymizing function name: " + methodName); final Object anonymizedValue = selectedMethod.invoke(instance); log.debug("anonymizedValue " + anonymizedValue); if (anonymizedValue == null) { return null; } log.debug(returnType); if (returnType == String.class) { return anonymizedValue.toString(); } else if (returnType == java.sql.Date.class) { return anonymizedValue; } else if ("int".equals(returnType)) { return anonymizedValue; } } catch (InstantiationException | ClassNotFoundException ex) { log.error(ex.toString()); } return ""; }
From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java
/** * Invokes a method compatible to the specified parameters. * * @param instance the object on which to invoke the * method (must not be * <code>null</code>). * @param methodName the name of the method to invoke (must * not be <code>null</code>). * @param parameters the method parameters (as JSON * objects - must not be * <code>null</code>). * * @exception Exception thrown if the method cannot be found * or if invoking it fails. If the method * cannot be found, a * <code>NoSuchMethodException</code> is * thrown. *///from w ww .j a v a 2 s . com protected Object callCompatibleMethod(Object instance, String methodName, JSONArray parameters) throws Exception { Class clazz = instance.getClass(); StringBuffer cacheKeyBuffer = new StringBuffer(clazz.getName()); cacheKeyBuffer.append('-'); cacheKeyBuffer.append(methodName); int parameterCount = parameters.length(); Object parameter; int i; for (i = 0; i < parameterCount; ++i) { parameter = parameters.get(i); cacheKeyBuffer.append('-'); cacheKeyBuffer.append(parameter == null ? null : parameter.getClass().getName()); } String cacheKey = cacheKeyBuffer.toString(); Method method = (Method) _methodCache.get(cacheKey); Class[] methodParameterTypes; Object[] convertedParameters = new Object[parameterCount]; String lastError = null; if (method == null) { Method[] methods = clazz.getMethods(); Method candidate; int methodCount = methods.length; for (i = 0; i < methodCount; ++i) { candidate = methods[i]; if (!candidate.getName().equals(methodName)) { continue; } if (!throwsExpectedException(candidate)) { continue; } methodParameterTypes = candidate.getParameterTypes(); if (methodParameterTypes.length != parameterCount) { continue; } try { convertParameters(parameters, convertedParameters, methodParameterTypes); } catch (Exception e) { lastError = e.getMessage(); continue; } method = candidate; break; } if (method == null) { if (lastError == null) { throw new NoSuchMethodException(methodName); } throw new NoSuchMethodException(methodName + " - " + lastError); } _methodCache.put(cacheKey, method); return method.invoke(instance, convertedParameters); } try { convertParameters(parameters, convertedParameters, method.getParameterTypes()); } catch (Exception e) { // maybe it works with another method - not very fast from a // performance standpoint, but supports a variety of methods _methodCache.remove(cacheKey); return callCompatibleMethod(instance, methodName, parameters); } return method.invoke(instance, convertedParameters); }
From source file:org.forgerock.openidm.script.impl.ScriptRegistryService.java
protected void bindCryptoService(final CryptoService cryptoService) { // hash(any value, string algorithm) openidm.put("hash", new Function<JsonValue>() { static final long serialVersionUID = 1L; public JsonValue call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments.length == 2) { JsonValue value = null;/* ww w .jav a 2 s . c o m*/ String algorithm = null; if (arguments[0] instanceof Map || arguments[0] instanceof List || arguments[0] instanceof String || arguments[0] instanceof Number || arguments[0] instanceof Boolean) { value = new JsonValue(arguments[0]); } else if (arguments[0] instanceof JsonValue) { value = (JsonValue) arguments[0]; } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("hash", arguments)); } if (arguments[1] instanceof String) { algorithm = (String) arguments[1]; } else if (arguments[1] == null) { algorithm = ServerConstants.SECURITY_CRYPTOGRAPHY_DEFAULT_HASHING_ALGORITHM; } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("hash", arguments)); } try { return cryptoService.hash(value, algorithm); } catch (JsonCryptoException e) { throw new InternalServerErrorException(e.getMessage(), e); } } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("hash", arguments)); } } }); // encrypt(any value, string cipher, string alias) openidm.put("encrypt", new Function<JsonValue>() { static final long serialVersionUID = 1L; public JsonValue call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments.length == 3) { JsonValue value = null; String cipher = null; String alias = null; if (arguments[0] instanceof Map || arguments[0] instanceof List || arguments[0] instanceof String || arguments[0] instanceof Number || arguments[0] instanceof Boolean) { value = new JsonValue(arguments[0]); } else if (arguments[0] instanceof JsonValue) { value = (JsonValue) arguments[0]; } else { throw new NoSuchMethodException( FunctionFactory.getNoSuchMethodMessage("encrypt", arguments)); } if (arguments[1] instanceof String) { cipher = (String) arguments[1]; } else if (arguments[1] == null) { cipher = ServerConstants.SECURITY_CRYPTOGRAPHY_DEFAULT_CIPHER; } else { throw new NoSuchMethodException( FunctionFactory.getNoSuchMethodMessage("encrypt", arguments)); } if (arguments[2] instanceof String) { alias = (String) arguments[2]; } else { throw new NoSuchMethodException( FunctionFactory.getNoSuchMethodMessage("encrypt", arguments)); } try { return cryptoService.encrypt(value, cipher, alias); } catch (JsonCryptoException e) { throw new InternalServerErrorException(e.getMessage(), e); } } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("encrypt", arguments)); } } }); // decrypt(any value) openidm.put("decrypt", new Function<JsonValue>() { static final long serialVersionUID = 1L; public JsonValue call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments.length == 1 && (arguments[0] instanceof Map || arguments[0] instanceof JsonValue)) { return cryptoService.decrypt(arguments[0] instanceof JsonValue ? (JsonValue) arguments[0] : new JsonValue(arguments[0])); } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("decrypt", arguments)); } } }); // isEncrypted(any value) openidm.put("isEncrypted", new Function<Boolean>() { static final long serialVersionUID = 1L; public Boolean call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments == null || arguments.length == 0) { return false; } else if (arguments.length == 1) { return JsonCrypto.isJsonCrypto(arguments[0] instanceof JsonValue ? (JsonValue) arguments[0] : new JsonValue(arguments[0])); } else { throw new NoSuchMethodException( FunctionFactory.getNoSuchMethodMessage("isEncrypted", arguments)); } } }); // isHashed(any value) openidm.put("isHashed", new Function<Boolean>() { static final long serialVersionUID = 1L; public Boolean call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments == null || arguments.length == 0) { return false; } else if (arguments.length == 1) { return cryptoService.isHashed(arguments[0] instanceof JsonValue ? (JsonValue) arguments[0] : new JsonValue(arguments[0])); } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("isHashed", arguments)); } } }); // matches(String plaintext, any value) openidm.put("matches", new Function<Boolean>() { static final long serialVersionUID = 1L; public Boolean call(Parameter scope, Function<?> callback, Object... arguments) throws ResourceException, NoSuchMethodException { if (arguments == null || arguments.length == 0 || arguments.length == 1) { return false; } else if (arguments.length == 2) { try { return cryptoService.matches(arguments[0].toString(), arguments[1] instanceof JsonValue ? (JsonValue) arguments[1] : new JsonValue(arguments[1])); } catch (JsonCryptoException e) { throw new InternalServerErrorException(e.getMessage(), e); } } else { throw new NoSuchMethodException(FunctionFactory.getNoSuchMethodMessage("matches", arguments)); } } }); logger.info("Crypto functions are enabled"); }
From source file:org.grouplens.lenskit.eval.script.ConfigMethodInvoker.java
/** * Find an external method (a builder or task) and return a closure that, when invoked, * constructs and configures it. It does <strong>not</strong> invoke the builder or task, that * is left up to the caller.// w w w . ja va2 s. c o m * * @param name The method name. * @return The constructed and configured object corresponding to this method. */ public Object callExternalMethod(String name, Object... args) throws NoSuchMethodException { final Class<?> mtype = engine.lookupMethod(name); if (mtype != null) { try { return constructAndConfigure(mtype, args); } catch (NoSuchMethodException e) { throw new RuntimeException("cannot find suitable for " + mtype.toString(), e); } } else { throw new NoSuchMethodException(name); } }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * Return the value of the specified indexed property of the specified * bean, with no type conversions. In addition to supporting the JavaBeans * specification, this method has been extended to support * <code>List</code> objects as well. * * @param bean Bean whose property is to be extracted * @param name Simple property name of the property value to be extracted * @param index Index of the property value to be extracted * * @exception ArrayIndexOutOfBoundsException if the specified index * is outside the valid range for the underlying array * @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 InvocationTargetException if the property accessor method * throws an exception//from w ww .ja v a 2 s . c o m * @exception NoSuchMethodException if an accessor method for this * propety cannot be found */ public Object getIndexedProperty(Object bean, String name, int index) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { throw new IllegalArgumentException("No bean specified"); } if (name == null) { throw new IllegalArgumentException("No name specified"); } // Handle DynaBean instances specially if (bean instanceof DynaBean) { DynaProperty descriptor = ((DynaBean) bean).getDynaClass().getDynaProperty(name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'"); } return (((DynaBean) bean).get(name, index)); } // Retrieve the property descriptor for the specified property PropertyDescriptor descriptor = getPropertyDescriptor(bean, name); if (descriptor == null) { throw new NoSuchMethodException("Unknown property '" + name + "'"); } // Call the indexed getter method if there is one if (descriptor instanceof IndexedPropertyDescriptor) { Method readMethod = ((IndexedPropertyDescriptor) descriptor).getIndexedReadMethod(); if (readMethod != null) { Object subscript[] = new Object[1]; subscript[0] = new Integer(index); try { return (invokeMethod(readMethod, bean, subscript)); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof ArrayIndexOutOfBoundsException) { throw (ArrayIndexOutOfBoundsException) e.getTargetException(); } else { throw e; } } } } // Otherwise, the underlying property must be an array Method readMethod = getReadMethod(descriptor); if (readMethod == null) { throw new NoSuchMethodException("Property '" + name + "' has no getter method"); } // Call the property getter and return the value Object value = invokeMethod(readMethod, bean, new Object[0]); if (!value.getClass().isArray()) { if (!(value instanceof java.util.List)) { throw new IllegalArgumentException("Property '" + name + "' is not indexed"); } else { //get the List's value return ((java.util.List) value).get(index); } } else { //get the array's value return (Array.get(value, index)); } }
From source file:org.jabsorb.JSONRPCBridge.java
/** * Call a method using a JSON-RPC request object. * * @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.//from w w w. ja v a 2 s.c o m */ public JSONRPCResult call(Object context[], JSONObject jsonReq) { // #1: Parse the request final String encodedMethod; final Object requestId; final JSONArray arguments; final JSONArray fixups; try { encodedMethod = jsonReq.getString("method"); arguments = jsonReq.getJSONArray("params"); requestId = jsonReq.opt("id"); fixups = jsonReq.optJSONArray("fixups"); } catch (JSONException e) { log.error("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 " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId); } else { log.debug("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++) { JSONArray assignment = fixups.getJSONArray(i); JSONArray fixup = assignment.getJSONArray(0); JSONArray original = assignment.getJSONArray(1); applyFixup(arguments, fixup, original); } } catch (JSONException e) { log.error("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; { 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, getSystemMethods()); } // #5: Get the object to act upon and the possible method that could be // called on it final Map 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 (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 JSONRPCResult r = AccessibleObjectResolver.invokeAccessibleObject(ao, context, arguments, javascriptObject, requestId, ser, cbc, exceptionTransformer); return r; }
From source file:com.link_intersystems.lang.reflect.Class2.java
/** * * @param method/*from w ww. ja va2s . co m*/ * @return the {@link Method2} for the given {@link Method}. The * {@link Method} must be declared on this {@link Class2}'s * {@link Class}. * @throws NoSuchMethodException * if the method is not declared on this {@link Class2}'s * {@link Class}. * @since 1.0.0.0 */ Method2 getMethod2(Method method) throws NoSuchMethodException { Assert.notNull("method", method); List<Method2> declaredMethods = getDeclaredMethods(); for (Method2 method2 : declaredMethods) { if (method.equals(method2.getMember())) { return method2; } } throw new NoSuchMethodException(method + " must be a method of this " + clazz); }
From source file:eu.qualityontime.commons.MethodUtils.java
/** * <p>/* w ww . ja v a 2 s .c o m*/ * Invoke a static method whose parameter types match exactly the parameter * types given. * </p> * * <p> * This uses reflection to invoke the method obtained from a call to * {@link #getAccessibleMethod(Class, String, Class[])}. * </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 invokeExactStaticMethod(final Class<?> objectClass, final String methodName, Object[] args, Class<?>[] parameterTypes) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { if (args == null) { args = EMPTY_OBJECT_ARRAY; } if (parameterTypes == null) { parameterTypes = EMPTY_CLASS_PARAMETERS; } final Method method = getAccessibleMethod(objectClass, methodName, parameterTypes); if (method == null) { throw new NoSuchMethodException( "No such accessible method: " + methodName + "() on class: " + objectClass.getName()); } return method.invoke(null, args); }