List of usage examples for java.lang.reflect Method getDeclaringClass
@Override
public Class<?> getDeclaringClass()
From source file:com.freetmp.common.util.ClassUtils.java
public static Method getMostSpecificMethod(Method method, Class<?> targetClass) { if (method != null && isOverridable(method, targetClass) && targetClass != null && !targetClass.equals(method.getDeclaringClass())) { try {/*from w w w . j av a2 s .c o m*/ if (Modifier.isPublic(method.getModifiers())) { try { return targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { return method; } } else { Method specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes()); return (specificMethod != null ? specificMethod : method); } } catch (SecurityException ex) { // Security settings are disallowing reflective access; fall back to 'method' below. } } return method; }
From source file:com.link_intersystems.beans.BeanClass.java
/** * Returns true if the method is a method to access a property (either get, * is, set). The equality is based on the method's signature. This means * that even property accessor methods in super classes will be recognized * as property accessor methods of this {@link BeanClass}. * * @param method/*w ww. j ava 2s .c om*/ * the method to test if it is a property accessor method of this * class. * @return true if the given method is a property accessor method of this * class. * @since 1.2.0.0 */ @SuppressWarnings("unchecked") public boolean isPropertyAccessor(Method method) { Class<?> declaringClass = method.getDeclaringClass(); Class<T> beanType = getType(); boolean isInHierarchy = declaringClass.isAssignableFrom(beanType); if (!isInHierarchy) { return false; } Map<String, PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(); Collection<PropertyDescriptor> propertyDescriptorCollection = propertyDescriptors.values(); Predicate predicate = new SignaturePredicate(method); Iterator<Method> propertyMethodsIterator = IteratorUtils.objectGraphIterator( propertyDescriptorCollection.iterator(), PropertyDescriptor2AccessorsTransformer.INSTANCE); Iterator<Method> filteredIterator = IteratorUtils.filteredIterator(propertyMethodsIterator, predicate); return filteredIterator.hasNext(); }
From source file:org.apache.tuscany.sca.binding.jsonrpc.provider.JsonRpcInvoker.java
/** * Generate and throw exception based on the data in the 'responseMessage' *//*from w w w .j av a2s . c o m*/ protected void processException(ObjectNode responseMessage) throws Throwable { // FIXME: We need to find a way to build Java exceptions out of the json-rpc error JsonNode error = responseMessage.get("error"); if (error != null) { Object data = error.get("data"); if (data instanceof ObjectNode) { ObjectNode fault = (ObjectNode) data; String javaClass = opt(fault, "class"); String message = opt(fault, "message"); String stackTrace = opt(fault, "stackTrace"); if (javaClass != null) { if (stackTrace != null) { message = message + "\n" + stackTrace; } ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (operation instanceof JavaOperation) { Method method = ((JavaOperation) operation).getJavaMethod(); classLoader = method.getDeclaringClass().getClassLoader(); } Class<? extends Throwable> exceptionClass = (Class<? extends Throwable>) Class .forName(javaClass, false, classLoader); Constructor<? extends Throwable> ctor = null; Throwable ex = null; try { ctor = exceptionClass.getConstructor(String.class, Throwable.class); ex = ctor.newInstance(message, null); } catch (NoSuchMethodException e1) { try { ctor = exceptionClass.getConstructor(String.class); ex = ctor.newInstance(message); } catch (NoSuchMethodException e2) { try { ctor = exceptionClass.getConstructor(Throwable.class); ex = ctor.newInstance(null); } catch (NoSuchMethodException e3) { ctor = exceptionClass.getConstructor(); ex = ctor.newInstance(); } } } throw ex; } } throw new ServiceRuntimeException(error.toString()); } }
From source file:hydrograph.ui.expression.editor.evaluate.EvaluateExpression.java
@SuppressWarnings({ "unchecked" }) String invokeEvaluateFunctionFromJar(String expression, String[] fieldNames, Object[] values) { LOGGER.debug("Evaluating expression from jar"); String output = null;/*from w w w .j a v a 2s .co m*/ Object[] returnObj; expression = ValidateExpressionToolButton.getExpressionText(expression); URLClassLoader child = null; try { returnObj = ValidateExpressionToolButton.getBuildPathForMethodInvocation(); List<URL> urlList = (List<URL>) returnObj[0]; String userFunctionsPropertyFileName = (String) returnObj[2]; child = URLClassLoader.newInstance(urlList.toArray(new URL[urlList.size()])); Thread.currentThread().setContextClassLoader(child); Class<?> class1 = Class.forName( ValidateExpressionToolButton.HYDROGRAPH_ENGINE_EXPRESSION_VALIDATION_API_CLASS, true, child); Method[] methods = class1.getDeclaredMethods(); for (Method method : methods) { if (method.getParameterTypes().length == 4 && StringUtils.equals(method.getName(), EVALUATE_METHOD_OF_EXPRESSION_JAR)) { method.getDeclaringClass().getClassLoader(); output = String.valueOf( method.invoke(null, expression, userFunctionsPropertyFileName, fieldNames, values)); break; } } } catch (JavaModelException | MalformedURLException | ClassNotFoundException | IllegalAccessException | IllegalArgumentException exception) { evaluateDialog.showError(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION); LOGGER.error(Messages.ERROR_OCCURRED_WHILE_EVALUATING_EXPRESSION, exception); } catch (InvocationTargetException | RuntimeException exception) { if (exception.getCause().getCause() != null) { if (StringUtils.equals(exception.getCause().getCause().getClass().getSimpleName(), TARGET_ERROR_EXCEPTION_CLASS)) { evaluateDialog.showError(getTargetException(exception.getCause().getCause().toString())); } else evaluateDialog.showError(exception.getCause().getCause().getMessage()); } else evaluateDialog.showError(exception.getCause().getMessage()); LOGGER.debug("Invalid Expression....", exception); } finally { if (child != null) { try { child.close(); } catch (IOException ioException) { LOGGER.error("Error occurred while closing classloader", ioException); } } } return output; }
From source file:com.github.lightdocs.ModelBuilder.java
/** * Builds a documentation model from a list of JAXRS annotated classes. * /*from www. jav a 2s . com*/ * @param jaxrsClasses * required non empty list of classes or interfaces * @return a ServiceDocumentation object */ public ServiceDocumentation buildModelFor(String... jaxrsClasses) { Validate.notEmpty(jaxrsClasses); ServiceDocumentation model = new ServiceDocumentation(); for (String className : jaxrsClasses) { Class<?> clazz = loadClass(className); Validate.isTrue(hasPathAnnotation(clazz), "No JAXRS annotations were present on " + clazz); for (Method method : clazz.getMethods()) { if (hasHttpMethodAnnotation(method)) { Resource resource = model.resource(getRootResourceURIFor(method.getDeclaringClass())); HttpMethod operationMethod = HttpMethod.valueOf(findJAXRSHttpMethodAnnotation(method).value()); String classPathValue = standardizePathAnnotationValue( method.getDeclaringClass().getAnnotation(Path.class)); String methodPathValue = standardizePathAnnotationValue(method.getAnnotation(Path.class)); String operationPath = buildEffectiveURIFor(classPathValue, methodPathValue); Operation operation = resource.operation(operationMethod, operationPath); eventBus.post(new OperationAddedEvent(method, operation)); } } } return model; }
From source file:org.crazydog.util.spring.ClassUtils.java
/** * Given a method, which may come from an interface, and a target class used * in the current reflective invocation, find the corresponding target method * if there is one. E.g. the method may be {@code IFoo.bar()} and the * target class may be {@code DefaultFoo}. In this case, the method may be * {@code DefaultFoo.bar()}. This enables attributes on that method to be found. * <p><b>NOTE:</b> In contrast to {@link org.springframework.aop.support.AopUtils#getMostSpecificMethod}, * this method does <i>not</i> resolve Java 5 bridge methods automatically. * Call {@link org.springframework.core.BridgeMethodResolver#findBridgedMethod} * if bridge method resolution is desirable (e.g. for obtaining metadata from * the original method definition)./*from ww w .ja va 2 s .c om*/ * <p><b>NOTE:</b> Since Spring 3.1.1, if Java security settings disallow reflective * access (e.g. calls to {@code Class#getDeclaredMethods} etc, this implementation * will fall back to returning the originally provided method. * @param method the method to be invoked, which may come from an interface * @param targetClass the target class for the current invocation. * May be {@code null} or may not even implement the method. * @return the specific target method, or the original method if the * {@code targetClass} doesn't implement it or is {@code null} */ public static Method getMostSpecificMethod(Method method, Class<?> targetClass) { if (method != null && isOverridable(method, targetClass) && targetClass != null && !targetClass.equals(method.getDeclaringClass())) { try { if (Modifier.isPublic(method.getModifiers())) { try { return targetClass.getMethod(method.getName(), method.getParameterTypes()); } catch (NoSuchMethodException ex) { return method; } } else { Method specificMethod = ReflectionUtils.findMethod(targetClass, method.getName(), method.getParameterTypes()); return (specificMethod != null ? specificMethod : method); } } catch (SecurityException ex) { // Security settings are disallowing reflective access; fall back to 'method' below. } } return method; }
From source file:com.yqboots.security.core.audit.SecurityAuditProvider.java
/** * {@inheritDoc}/*from w ww .j a va 2 s .c o m*/ */ @Override public void afterInvocation(Method method, Object[] arguments, Object returnObj) { for (AuditProvider delegate : delegates) { if (delegate.supports(method.getDeclaringClass())) { delegate.afterInvocation(method, arguments, returnObj); } } }
From source file:ai.general.net.MethodHandler.java
/** * The specified instance must be an instance of the class that defines the method or a * subclass of that class. It may be null for static methods. * * The method must be publicly accessible and it must be defined public in a class that is * public. If the method is defined in a nested class, both the nested class and the outer class * must be public.// www .j a v a 2 s . c o m * * Event methods must have exactly 1 parameter that accepts the publish or event data. * Any return values or exceptions thrown by an event method will be ignored. * * RPC call methods may have any number of parameters, return any value and throw exceptions. * * Method parameters must hava a POJO type. This includes primitive Java types or their arrays, * and bean types, i.e. classes that declare getters and setters for each field. * * @param name A unique name for the MethodHandler. * @param catchall True if this a catch-all handler. * @param instance Instance associated with method. May be null for static methods. * @param method The method to be called. * @throws IllegalArgumentException if the arguments are invalid or incompatible with each other. */ public MethodHandler(String name, boolean catchall, Object instance, Method method) { super(name, catchall); if (!Modifier.isStatic(method.getModifiers())) { if (instance == null) { throw new IllegalArgumentException("Non-static method requires instance."); } if (!method.getDeclaringClass().isInstance(instance)) { throw new IllegalArgumentException("Incompatible instance object."); } } this.instance_ = instance; this.method_ = method; parameter_types_ = method.getParameterTypes(); json_parser_ = new ObjectMapper(); }
From source file:javadz.beanutils.MethodUtils.java
/** * <p>Return an accessible method (that is, one that can be invoked via * reflection) that implements the specified Method. If no such method * can be found, return <code>null</code>.</p> * * @param method The method that we wish to call * @return The accessible method/*from w ww .j a va2 s.c o m*/ */ public static Method getAccessibleMethod(Method method) { // Make sure we have a method to check if (method == null) { return (null); } return getAccessibleMethod(method.getDeclaringClass(), method); }
From source file:objenome.util.ClassUtils.java
/** * <p>Returns the desired Method much like {@code Class.getMethod}, however * it ensures that the returned Method is from a public class or interface and not * from an anonymous inner class. This means that the Method is invokable and * doesn't fall foul of Java bug/*from w w w . ja v a2s . c o m*/ * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).</p> * * <pre> * <code>Set set = Collections.unmodifiableSet(...); * Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty", new Class[0]); * Object result = method.invoke(set, new Object[]);</code> * </pre> * * @param cls the class to check, not null * @param methodName the name of the method * @param parameterTypes the list of parameters * @return the method * @throws NullPointerException if the class is null * @throws SecurityException if a security violation occurred * @throws NoSuchMethodException if the method is not found in the given class * or if the method doesn't conform with the requirements */ public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes) throws SecurityException, NoSuchMethodException { Method declaredMethod = cls.getMethod(methodName, parameterTypes); if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) { return declaredMethod; } List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls)); candidateClasses.addAll(getAllSuperclasses(cls)); for (Class<?> candidateClass : candidateClasses) { if (!Modifier.isPublic(candidateClass.getModifiers())) { continue; } Method candidateMethod; try { candidateMethod = candidateClass.getMethod(methodName, parameterTypes); } catch (NoSuchMethodException ex) { continue; } if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) { return candidateMethod; } } throw new NoSuchMethodException( "Can't find a public method for " + methodName + ' ' + ArrayUtils.toString(parameterTypes)); }