List of usage examples for java.lang NoSuchMethodException NoSuchMethodException
public NoSuchMethodException(String s)
NoSuchMethodException
with a detail message. From source file:com.austin.base.commons.util.ReflectUtil.java
/** * @param object//from www . ja v a2s. c om * @param methodName * @param params * @return * @throws NoSuchMethodException */ public static Object invokePrivateMethod(Object object, String methodName, Object... params) throws NoSuchMethodException { Assert.notNull(object); Assert.hasText(methodName); Class[] types = new Class[params.length]; for (int i = 0; i < params.length; i++) { types[i] = params[i].getClass(); } Class clazz = object.getClass(); Method method = null; for (Class superClass = clazz; superClass != Object.class; superClass = superClass.getSuperclass()) { try { method = superClass.getDeclaredMethod(methodName, types); break; } catch (NoSuchMethodException e) { // ??17,? } } if (method == null) throw new NoSuchMethodException("No Such Method:" + clazz.getSimpleName() + methodName); boolean accessible = method.isAccessible(); method.setAccessible(true); Object result = null; try { result = method.invoke(object, params); } catch (Exception e) { ReflectionUtils.handleReflectionException(e); } method.setAccessible(accessible); return result; }
From source file:org.dozer.util.ReflectionUtils.java
/** * Find a method with concrete string representation of it's parameters * @param clazz clazz to search//from w ww .j a v a2 s . co m * @param methodName name of method with representation of it's parameters * @return found method * @throws NoSuchMethodException */ public static Method findAMethod(Class<?> clazz, String methodName) throws NoSuchMethodException { StringTokenizer tokenizer = new StringTokenizer(methodName, "("); String m = tokenizer.nextToken(); Method result; // If tokenizer has more elements, it mean that parameters may have been specified if (tokenizer.hasMoreElements()) { StringTokenizer tokens = new StringTokenizer(tokenizer.nextToken(), ")"); String params = (tokens.hasMoreTokens() ? tokens.nextToken() : null); result = findMethodWithParam(clazz, m, params); } else { result = findMethod(clazz, methodName); } if (result == null) { throw new NoSuchMethodException(clazz.getName() + "." + methodName); } return result; }
From source file:edu.umich.flowfence.sandbox.ResolvedQM.java
private InstanceMethodData resolveInstance(Class<?> definingClass, String methodName, Class<?>[] paramClasses, boolean bestMatch) throws Exception { if (localLOGD) { Log.d(TAG, "Resolving as instance"); }/* w w w. j a v a 2 s .c om*/ final Method method = definingClass.getMethod(methodName, paramClasses); if (Modifier.isStatic(method.getModifiers())) { throw new NoSuchMethodException("Method is static, but was resolved as instance"); } return new InstanceMethodData(method); }
From source file:com.bstek.dorado.config.definition.Definition.java
/** * ?/* w w w . j a va 2s . c om*/ * * @param object * ? * @param property * ?? * @param value * @see {@link #getProperties()} * @param context * * @throws Exception */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void setObjectProperty(Object object, String property, Object value, CreationContext context) throws Exception { if (object instanceof Map) { value = DefinitionUtils.getRealValue(value, context); if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { ((Map) object).put(property, value); } } else { PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property); if (propertyDescriptor != null) { Method readMethod = propertyDescriptor.getReadMethod(); Method writeMethod = propertyDescriptor.getWriteMethod(); Class<?> propertyType = propertyDescriptor.getPropertyType(); if (writeMethod != null) { Class<?> oldImpl = context.getDefaultImpl(); try { context.setDefaultImpl(propertyType); value = DefinitionUtils.getRealValue(value, context); } finally { context.setDefaultImpl(oldImpl); } if (!propertyType.equals(String.class) && value instanceof String) { if (propertyType.isEnum()) { value = Enum.valueOf((Class) propertyType, (String) value); } else if (StringUtils.isBlank((String) value)) { value = null; } } else if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { List collection = new ArrayList(); for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } value = collection; } if (value != ConfigUtils.IGNORE_VALUE) { writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) }); } } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) { Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS); if (collection != null) { if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) { for (Object element : (Collection) value) { Object realElement = DefinitionUtils.getRealValue(element, context); if (realElement != ConfigUtils.IGNORE_VALUE) { collection.add(realElement); } } } else { collection.addAll((Collection) value); } } } else { throw new NoSuchMethodException( "Property [" + property + "] of [" + object + "] is not writable."); } } else { throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "]."); } } }
From source file:edu.umich.flowfence.sandbox.ResolvedQM.java
private MethodData resolveStatic(Class<?> definingClass, String methodName, Class<?>[] paramClasses, boolean bestMatch) throws Exception { if (localLOGD) { Log.d(TAG, "Resolving as static"); }// ww w. j av a2 s . co m final Method method = definingClass.getMethod(methodName, paramClasses); if (!Modifier.isStatic(method.getModifiers())) { throw new NoSuchMethodException("Method is instance, but was resolved as static"); } return new MethodData(method); }
From source file:com.github.dozermapper.core.util.ReflectionUtils.java
/** * Find a method with concrete string representation of it's parameters * * @param clazz clazz to search//from ww w . j av a2 s. co m * @param methodName name of method with representation of it's parameters * @param beanContainer beanContainer instance * @return found method * @throws NoSuchMethodException if no method found */ public static Method findAMethod(Class<?> clazz, String methodName, BeanContainer beanContainer) throws NoSuchMethodException { StringTokenizer tokenizer = new StringTokenizer(methodName, "("); String m = tokenizer.nextToken(); Method result; // If tokenizer has more elements, it mean that parameters may have been specified if (tokenizer.hasMoreElements()) { StringTokenizer tokens = new StringTokenizer(tokenizer.nextToken(), ")"); String params = tokens.hasMoreTokens() ? tokens.nextToken() : null; result = findMethodWithParam(clazz, m, params, beanContainer); } else { result = findMethod(clazz, methodName); } if (result == null) { throw new NoSuchMethodException(clazz.getName() + "." + methodName); } return result; }
From source file:org.apache.olingo.ext.proxy.commons.AbstractStructuredInvocationHandler.java
@Override public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { if (method.getName().startsWith("get")) { // Here need check "get"/"set" first for better get-/set- performance because // the below if-statements are really time-consuming, even twice slower than "get" body. // Assumption: for each getter will always exist a setter and viceversa. // get method annotation and check if it exists as expected final Object res; final Method getter = typeRef.getMethod(method.getName()); final Property property = ClassUtils.getAnnotation(Property.class, getter); if (property == null) { final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter); if (navProp == null) { throw new UnsupportedOperationException("Unsupported method " + method.getName()); } else { // if the getter refers to a navigation property ... navigate and follow link if necessary res = getNavigationPropertyValue(navProp, getter); }//from ww w . ja va2s. co m } else { // if the getter refers to a property .... get property from wrapped entity res = getPropertyValue(property.name(), getter.getGenericReturnType()); } return res; } else if (method.getName().startsWith("set")) { // get the corresponding getter method (see assumption above) final String getterName = method.getName().replaceFirst("set", "get"); final Method getter = typeRef.getMethod(getterName); final Property property = ClassUtils.getAnnotation(Property.class, getter); if (property == null) { final NavigationProperty navProp = ClassUtils.getAnnotation(NavigationProperty.class, getter); if (navProp == null) { throw new UnsupportedOperationException("Unsupported method " + method.getName()); } else { // if the getter refers to a navigation property ... if (ArrayUtils.isEmpty(args) || args.length != 1) { throw new IllegalArgumentException("Invalid argument"); } setNavigationPropertyValue(navProp, args[0]); } } else { setPropertyValue(property, args[0]); } return ClassUtils.returnVoid(); } else if ("expand".equals(method.getName()) || "select".equals(method.getName()) || "refs".equals(method.getName())) { invokeSelfMethod(method, args); return proxy; } else if (isSelfMethod(method)) { return invokeSelfMethod(method, args); } else if ("load".equals(method.getName()) && ArrayUtils.isEmpty(args)) { load(); return proxy; } else if ("loadAsync".equals(method.getName()) && ArrayUtils.isEmpty(args)) { return service.getClient().getConfiguration().getExecutor().submit(new Callable<Object>() { @Override public Object call() throws Exception { load(); return proxy; } }); } else if ("operations".equals(method.getName()) && ArrayUtils.isEmpty(args)) { final Class<?> returnType = method.getReturnType(); return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { returnType }, OperationInvocationHandler.getInstance(getEntityHandler())); } else if ("annotations".equals(method.getName()) && ArrayUtils.isEmpty(args)) { final Class<?> returnType = method.getReturnType(); return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[] { returnType }, AnnotatationsInvocationHandler.getInstance(getEntityHandler(), this)); } else { throw new NoSuchMethodException(method.getName()); } }
From source file:org.apache.struts.actions.ActionDispatcher.java
/** * Dispatch to the specified method.//from www .ja v a 2 s . c om */ protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, String name) throws Exception { // Make sure we have a valid method name to call. // This may be null if the user hacks the query string. if (name == null) { return this.unspecified(mapping, form, request, response); } // Identify the method object to be dispatched to Method method = null; try { method = getMethod(name); } catch (NoSuchMethodException e) { String message = messages.getMessage("dispatch.method", mapping.getPath(), name); log.error(message, e); String userMsg = messages.getMessage("dispatch.method.user", mapping.getPath()); throw new NoSuchMethodException(userMsg); } return dispatchMethod(mapping, form, request, response, name, method); }
From source file:org.ajax4jsf.templatecompiler.elements.vcp.FCallTemplateElement.java
/** * //from w w w. ja v a 2 s . c om * @param clazz * @param propertyName * @return */ private String getMethod(Class clazz, String methodName) throws ClassNotFoundException, NoSuchMethodException { String returnValue = null; Class[][] arrayParametersTypes = null; if (this.useOnlyEnumeratingParaments) { arrayParametersTypes = new Class[1][this.parameters.size()]; for (int i = 0; i < this.parameters.size(); i++) { arrayParametersTypes[0][i] = ((Parameter) this.parameters.get(i)).getType(); } } else { arrayParametersTypes = new Class[PARAM_NAMES.length + 1][]; for (int i = 0; i < arrayParametersTypes.length; i++) { int addlength = 0; if (i < PARAM_NAMES.length) { addlength = PARAM_NAMES[i].length; } arrayParametersTypes[i] = new Class[addlength + this.parameters.size()]; } for (int i = 0; i < PARAM_NAMES.length; i++) { for (int j = 0; j < PARAM_NAMES[i].length; j++) { arrayParametersTypes[i][j] = this.getComponentBean().getVariableType(PARAM_NAMES[i][j]); } } for (int i = 0; i < arrayParametersTypes.length; i++) { int shift = 0; if (i < PARAM_NAMES.length) { shift = PARAM_NAMES[i].length; } for (int j = 0; j < this.parameters.size(); j++) { Parameter parameter = (Parameter) this.parameters.get(j); arrayParametersTypes[i][shift + j] = parameter.getType(); } } } List<String> methodNotFoundMessagesList = new ArrayList<String>(); boolean found = false; for (int i = 0; i < arrayParametersTypes.length && !found; i++) { try { this.getComponentBean().getMethodReturnedClass(clazz, methodName, arrayParametersTypes[i]); StringBuffer buffer = new StringBuffer(); buffer.append(methodName); buffer.append("("); int shift = 0; if (i < PARAM_NAMES.length) { shift = PARAM_NAMES[i].length; } for (int j = 0; j < arrayParametersTypes[i].length; j++) { if (j > 0) { buffer.append(", "); } if ((i < PARAM_NAMES.length) && (j < PARAM_NAMES[i].length)) { buffer.append(PARAM_NAMES[i][j]); } else { Parameter parameter = (Parameter) this.parameters.get(j - shift); String tmp = ELParser.compileEL(parameter.getValue(), this.getComponentBean()); buffer.append(tmp); } } buffer.append(")"); returnValue = buffer.toString(); found = true; } catch (NoSuchMethodException e) { methodNotFoundMessagesList.add(e.getLocalizedMessage()); } } // for if (!found) { throw new NoSuchMethodException("Could not find methods: " + methodNotFoundMessagesList); } return returnValue; }
From source file:io.github.wysohn.triggerreactor.tools.ReflectionUtil.java
@SuppressWarnings({ "unchecked", "unchecked" }) public static Object invokeMethod(Class<?> clazz, Object obj, String methodName, Object... args) throws NoSuchMethodException, IllegalArgumentException, InvocationTargetException, IllegalAccessException {/*from ww w .jav a2s.c o m*/ try { List<Method> validMethods = new ArrayList<>(); for (Method method : clazz.getMethods()) { Class<?>[] parameterTypes = null; if (!method.getName().equals(methodName)) { continue; } parameterTypes = method.getParameterTypes(); if (method.isVarArgs()) { if (method.isVarArgs() && (parameterTypes.length - args.length >= 2)) { parameterTypes = null; continue; } } else { if (parameterTypes.length != args.length) { parameterTypes = null; continue; } } if (method.isVarArgs()) { boolean matches = false; // check non vararg part for (int i = 0; i < parameterTypes.length - 1; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } // check rest for (int i = parameterTypes.length - 1; i < args.length; i++) { Class<?> arrayType = parameterTypes[parameterTypes.length - 1].getComponentType(); matches = checkMatch(arrayType, args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } else { boolean matches = true; for (int i = 0; i < parameterTypes.length; i++) { matches = checkMatch(parameterTypes[i], args[i]); if (!matches) break; } if (matches) { validMethods.add(method); } } } if (!validMethods.isEmpty()) { Method method = validMethods.get(0); for (int i = 1; i < validMethods.size(); i++) { Method targetMethod = validMethods.get(i); Class<?>[] currentParams = method.getParameterTypes(); Class<?>[] targetParams = targetMethod.getParameterTypes(); if (method.isVarArgs() && targetMethod.isVarArgs()) { for (int j = 0; j < currentParams.length; j++) { if (currentParams[j].isAssignableFrom(targetParams[j])) { method = targetMethod; break; } } } else if (method.isVarArgs()) { //usually, non-vararg is more specific method. So we use that method = targetMethod; } else if (targetMethod.isVarArgs()) { //do nothing } else { for (int j = 0; j < currentParams.length; j++) { if (targetParams[j].isEnum()) { // enum will be handled later method = targetMethod; break; } else if (ClassUtils.isAssignable(targetParams[j], currentParams[j], true)) { //narrow down to find the most specific method method = targetMethod; break; } } } } method.setAccessible(true); for (int i = 0; i < args.length; i++) { Class<?>[] parameterTypes = method.getParameterTypes(); if (args[i] instanceof String && i < parameterTypes.length && parameterTypes[i].isEnum()) { try { args[i] = Enum.valueOf((Class<? extends Enum>) parameterTypes[i], (String) args[i]); } catch (IllegalArgumentException ex1) { // Some overloaded methods already has // String to Enum conversion // So just lets see if one exists Class<?>[] types = new Class<?>[args.length]; for (int k = 0; k < args.length; k++) types[k] = args[k].getClass(); try { Method alternative = clazz.getMethod(methodName, types); return alternative.invoke(obj, args); } catch (NoSuchMethodException ex2) { throw new RuntimeException( "Tried to convert value [" + args[i] + "] to Enum [" + parameterTypes[i] + "] or find appropriate method but found nothing. Make sure" + " that the value [" + args[i] + "] matches exactly with one of the Enums in [" + parameterTypes[i] + "] or the method you are looking exists."); } } } } if (method.isVarArgs()) { Class<?>[] parameterTypes = method.getParameterTypes(); Object varargs = Array.newInstance(parameterTypes[parameterTypes.length - 1].getComponentType(), args.length - parameterTypes.length + 1); for (int k = 0; k < Array.getLength(varargs); k++) { Array.set(varargs, k, args[parameterTypes.length - 1 + k]); } Object[] newArgs = new Object[parameterTypes.length]; for (int k = 0; k < newArgs.length - 1; k++) { newArgs[k] = args[k]; } newArgs[newArgs.length - 1] = varargs; args = newArgs; } return method.invoke(obj, args); } if (args.length > 0) { StringBuilder builder = new StringBuilder(String.valueOf(args[0].getClass().getSimpleName())); for (int i = 1; i < args.length; i++) { builder.append(", " + args[i].getClass().getSimpleName()); } throw new NoSuchMethodException(methodName + "(" + builder.toString() + ")"); } else { throw new NoSuchMethodException(methodName + "()"); } } catch (NullPointerException e) { StringBuilder builder = new StringBuilder(String.valueOf(args[0])); for (int i = 1; i < args.length; i++) builder.append("," + String.valueOf(args[i])); throw new NullPointerException("Call " + methodName + "(" + builder.toString() + ")"); } }