List of usage examples for org.springframework.util ReflectionUtils findMethod
@Nullable public static Method findMethod(Class<?> clazz, String name, @Nullable Class<?>... paramTypes)
From source file:com.px100systems.util.serialization.SerializationDefinition.java
private SerializationDefinition(Class<?> cls) { definitions.put(cls, this); if (cls.getName().startsWith("java")) throw new RuntimeException("System classes are not supported: " + cls.getSimpleName()); try {/*from w w w .j av a 2 s . com*/ constructor = cls.getConstructor(); } catch (NoSuchMethodException e) { throw new RuntimeException("Missing no-arg constructor: " + cls.getSimpleName()); } serializingSetter = ReflectionUtils.findMethod(cls, "setSerializing", boolean.class); for (Class<?> c = cls; c != null && !c.equals(Object.class); c = c.getSuperclass()) { for (Field field : c.getDeclaredFields()) { if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers())) continue; FieldDefinition fd = new FieldDefinition(); fd.name = field.getName(); fd.type = field.getType(); if (fd.type.isPrimitive()) throw new RuntimeException("Primitives are not supported: " + fd.type.getSimpleName()); Calculated calc = field.getAnnotation(Calculated.class); if (!fd.type.equals(Integer.class) && !fd.type.equals(Long.class) && !fd.type.equals(Double.class) && !fd.type.equals(Boolean.class) && !fd.type.equals(Date.class) && !fd.type.equals(String.class)) if (fd.type.equals(List.class) || fd.type.equals(Set.class)) { SerializedCollection sc = field.getAnnotation(SerializedCollection.class); if (sc == null) throw new RuntimeException( cls.getSimpleName() + "." + fd.name + " is missing @SerializedCollection"); if (calc != null) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " cannot have a calculator because it is a collection"); fd.collectionType = sc.type(); fd.primitive = fd.collectionType.equals(Integer.class) || fd.collectionType.equals(Long.class) || fd.collectionType.equals(Double.class) || fd.collectionType.equals(Boolean.class) || fd.collectionType.equals(Date.class) || fd.collectionType.equals(String.class); if (!fd.primitive) { if (cls.getName().startsWith("java")) throw new RuntimeException(cls.getSimpleName() + "." + fd.name + ": system collection types are not supported: " + fd.collectionType.getSimpleName()); if (!definitions.containsKey(fd.collectionType)) new SerializationDefinition(fd.collectionType); } } else { if (cls.getName().startsWith("java")) throw new RuntimeException( "System classes are not supported: " + fd.type.getSimpleName()); if (!definitions.containsKey(fd.type)) new SerializationDefinition(fd.type); } else fd.primitive = true; try { fd.accessor = c.getMethod(PropertyAccessor.methodName("get", fd.name)); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing getter"); } try { fd.mutator = c.getMethod(PropertyAccessor.methodName("set", fd.name), fd.type); } catch (NoSuchMethodException e) { throw new RuntimeException(cls.getSimpleName() + "." + fd.name + " is missing setter"); } if (calc != null) fd.calculator = new SpelExpressionParser().parseExpression(calc.value()); fields.add(fd); } for (Method method : c.getDeclaredMethods()) if (Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers()) && method.getName().startsWith("get") && method.isAnnotationPresent(SerializedGetter.class)) { FieldDefinition fd = new FieldDefinition(); fd.name = method.getName().substring(3); fd.name = fd.name.substring(0, 1).toLowerCase() + fd.name.substring(1); fd.type = method.getReturnType(); fd.primitive = fd.type != null && (fd.type.equals(Integer.class) || fd.type.equals(Long.class) || fd.type.equals(Double.class) || fd.type.equals(Boolean.class) || fd.type.equals(Date.class) || fd.type.equals(String.class)); if (!fd.primitive) throw new RuntimeException("Not compact-serializable getter type: " + (fd.type == null ? "void" : fd.type.getSimpleName())); fd.accessor = method; gettersOnly.add(fd); } } }
From source file:org.javelin.sws.ext.bind.internal.metadata.PropertyCallback.java
/** * Like {@link MethodCallback#doWith(Method)}, but for two methods. * // w ww .j ava 2 s . co m * @see org.springframework.util.ReflectionUtils.MethodCallback#doWith(java.lang.reflect.Method) */ @Override public void doWith(Method getter) throws IllegalArgumentException, IllegalAccessException { Method setter = ReflectionUtils.findMethod(clazz, getter.getName().replaceFirst("^get", "set"), getter.getReturnType()); if (log.isTraceEnabled()) { if (setter != null) { log.trace(" - Analyzing pair of methods: {}.{}/{}.{}", getter.getDeclaringClass().getSimpleName(), getter.getName(), setter.getDeclaringClass().getSimpleName(), setter.getName()); } else { // we have java.util.Collection log.trace(" - Analyzing method: {}.{}", getter.getDeclaringClass().getSimpleName(), getter.getName()); } } // TODO: properly handle class hierarchies String propertyName = StringUtils.uncapitalize(getter.getName().substring(3)); // metadata for getter/setter PropertyMetadata<T, ?> metadata = PropertyMetadata.newPropertyMetadata(this.clazz, getter.getReturnType(), propertyName, getter, setter, PropertyKind.BEAN); this.doWithPropertySafe(metadata); }
From source file:com.iisigroup.cap.utils.CapBeanUtil.java
public static <T> T setField(T entry, String fieldId, Object value) { Field field = ReflectionUtils.findField(entry.getClass(), fieldId); if (field != null) { String setter = new StringBuffer("set").append(String.valueOf(field.getName().charAt(0)).toUpperCase()) .append(field.getName().substring(1)).toString(); Method method = ReflectionUtils.findMethod(entry.getClass(), setter, new Class[] { field.getType() }); if (method != null) { try { if (field.getType() != String.class && "".equals(value)) { value = null;/*from ww w .j av a 2 s . c om*/ } else if (field.getType() == BigDecimal.class) { value = CapMath.getBigDecimal(String.valueOf(value)); } else if (value instanceof String) { if (field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) { value = CapDate.parseDate((String) value); } else if (field.getType() == Timestamp.class) { value = CapDate.convertStringToTimestamp1((String) value); } } if (value == null) { method.invoke(entry, new Object[] { null }); } else { method.invoke(entry, ConvertUtils.convert(value, field.getType())); } } catch (Exception e) { if (LOGGER.isTraceEnabled()) { LOGGER.trace(e.getMessage()); } else { LOGGER.warn(e.getMessage(), e); } } } } return entry; }
From source file:org.openspaces.pu.container.jee.jetty.JettyWebApplicationContextListener.java
public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext servletContext = servletContextEvent.getServletContext(); // a hack to get the jetty context final ServletContextHandler jettyContext = (ServletContextHandler) ((ContextHandler.Context) servletContext) .getContextHandler();/*from w w w . j a v a 2 s . co m*/ final SessionHandler sessionHandler = jettyContext.getSessionHandler(); BeanLevelProperties beanLevelProperties = (BeanLevelProperties) servletContext .getAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT); ClusterInfo clusterInfo = (ClusterInfo) servletContext .getAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT); if (beanLevelProperties != null) { // automatically enable GigaSpaces Session Manager when passing the relevant property String sessionsSpaceUrl = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_URL); if (sessionsSpaceUrl != null) { logger.info("Jetty GigaSpaces Session support using space url [" + sessionsSpaceUrl + "]"); GigaSessionManager gigaSessionManager = new GigaSessionManager(); if (sessionsSpaceUrl.startsWith("bean://")) { ApplicationContext applicationContext = (ApplicationContext) servletContext .getAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT); if (applicationContext == null) { throw new IllegalStateException("Failed to find servlet context bound application context"); } GigaSpace space; Object bean = applicationContext.getBean(sessionsSpaceUrl.substring("bean://".length())); if (bean instanceof GigaSpace) { space = (GigaSpace) bean; } else if (bean instanceof IJSpace) { space = new GigaSpaceConfigurer((IJSpace) bean).create(); } else { throw new IllegalArgumentException( "Bean [" + bean + "] is not of either GigaSpace type or IJSpace type"); } gigaSessionManager.setSpace(space); } else { gigaSessionManager.setUrlSpaceConfigurer( new UrlSpaceConfigurer(sessionsSpaceUrl).clusterInfo(clusterInfo)); } String scavangePeriod = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_SCAVENGE_PERIOD); if (scavangePeriod != null) { gigaSessionManager.setScavengePeriod(Integer.parseInt(scavangePeriod)); if (logger.isDebugEnabled()) { logger.debug("Setting scavenge period to [" + scavangePeriod + "] seconds"); } } String savePeriod = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_SAVE_PERIOD); if (savePeriod != null) { gigaSessionManager.setSavePeriod(Integer.parseInt(savePeriod)); if (logger.isDebugEnabled()) { logger.debug("Setting save period to [" + savePeriod + "] seconds"); } } String lease = beanLevelProperties.getContextProperties().getProperty(JETTY_SESSIONS_LEASE); if (lease != null) { gigaSessionManager.setLease(Long.parseLong(lease)); if (logger.isDebugEnabled()) { logger.debug("Setting lease to [" + lease + "] milliseconds"); } } // copy over session settings SessionManager sessionManager = sessionHandler.getSessionManager(); gigaSessionManager.getSessionCookieConfig() .setName(sessionManager.getSessionCookieConfig().getName()); gigaSessionManager.getSessionCookieConfig() .setDomain(sessionManager.getSessionCookieConfig().getDomain()); gigaSessionManager.getSessionCookieConfig() .setPath(sessionManager.getSessionCookieConfig().getPath()); gigaSessionManager.setUsingCookies(sessionManager.isUsingCookies()); gigaSessionManager.getSessionCookieConfig() .setMaxAge(sessionManager.getSessionCookieConfig().getMaxAge()); gigaSessionManager.getSessionCookieConfig() .setSecure(sessionManager.getSessionCookieConfig().isSecure()); gigaSessionManager.setMaxInactiveInterval(sessionManager.getMaxInactiveInterval()); gigaSessionManager.setHttpOnly(sessionManager.getHttpOnly()); gigaSessionManager.getSessionCookieConfig() .setComment(sessionManager.getSessionCookieConfig().getComment()); String sessionTimeout = beanLevelProperties.getContextProperties() .getProperty(JETTY_SESSIONS_TIMEOUT); if (sessionTimeout != null) { gigaSessionManager.setMaxInactiveInterval(Integer.parseInt(sessionTimeout) * 60); if (logger.isDebugEnabled()) { logger.debug("Setting session timeout to [" + sessionTimeout + "] seconds"); } } GigaSessionIdManager sessionIdManager = new GigaSessionIdManager(jettyContext.getServer()); sessionIdManager.setWorkerName(clusterInfo.getUniqueName().replace('.', '_')); gigaSessionManager.setIdManager(sessionIdManager); // replace the actual session manager inside the LazySessionManager with GS session manager, this is // because in Jetty 9 it no more possible to replace the session manager after the server started // without deleting all webapps. if ("GSLazySessionManager".equals(sessionManager.getClass().getSimpleName())) { try { Method method = ReflectionUtils.findMethod(sessionManager.getClass(), "replaceDefault", SessionManager.class); if (method != null) { ReflectionUtils.invokeMethod(method, sessionManager, gigaSessionManager); } else { throw new NoSuchMethodException("replaceDefault"); } } catch (Exception e) { throw new RuntimeException( "Failed to replace default session manager with GSSessionManager", e); } } } // if we have a simple hash session id manager, set its worker name automatically... if (sessionHandler.getSessionManager().getSessionIdManager() instanceof HashSessionIdManager) { HashSessionIdManager sessionIdManager = (HashSessionIdManager) sessionHandler.getSessionManager() .getSessionIdManager(); if (sessionIdManager.getWorkerName() == null) { final String workerName = clusterInfo.getUniqueName().replace('.', '_'); if (logger.isDebugEnabled()) { logger.debug("Automatically setting worker name to [" + workerName + "]"); } stop(sessionIdManager, "to set worker name"); sessionIdManager.setWorkerName(workerName); start(sessionIdManager, "to set worker name"); } } } }
From source file:com.aol.advertising.qiao.util.ContextUtils.java
/** * Supporting one parameter only./*w w w . j a v a 2s . c om*/ * * @param clazz * @param methodName * @param paramType * @return */ private static Method findMethod(Class<?> clazz, String methodName, Class<?> paramType) { // trace //System.out.println("findMethod> class=" + clazz.getSimpleName() // + ",method=" + methodName + ",param=" // + paramType.getSimpleName()); Method mth = ReflectionUtils.findMethod(clazz, methodName, paramType); if (mth == null) { // check param's interfaces Class<?>[] list = paramType.getInterfaces(); if (list != null && list.length > 0) { for (Class<?> c : list) { mth = findMethod(clazz, methodName, c); if (mth != null) return mth; } } // check param's super class Class<?> param_super = paramType.getSuperclass(); if (param_super != null) { mth = findMethod(clazz, methodName, param_super); if (mth != null) return mth; } if (mth == null) { // check object's super class Class<?> parent_clz = clazz.getSuperclass(); if (parent_clz != null) { mth = findMethod(parent_clz, methodName, paramType); } } } return mth; }
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)./* w w w.j a v a 2s . c o m*/ * <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:demo.ChildMethodRule.java
@Override public Statement apply(Statement base, FrameworkMethod frameworkMethod, Object testInstance) { Class<?> testClass = testInstance.getClass(); Method method = ReflectionUtils.findMethod(SpringClassRule.class, "getTestContextManager", Class.class); ReflectionUtils.makeAccessible(method); TestContextManager testContextManager = (TestContextManager) ReflectionUtils.invokeMethod(method, null, testClass);//from w w w . j a v a 2s . c o m TestContext testContext = (TestContext) ReflectionTestUtils.getField(testContextManager, "testContext"); if (logger.isDebugEnabled()) { logger.debug("Applying ChildMethodRule to test method [" + frameworkMethod.getMethod() + "]."); } return new Statement() { @Override public void evaluate() throws Throwable { delegate(base, frameworkMethod, testInstance, testContext); } }; }
From source file:org.alfresco.rest.framework.core.ResourceInspector.java
/** * Returns the method for the interface//from ww w .java 2 s.c o m * @return null or a Method */ public static Method findMethod(Class<? extends ResourceAction> resourceInterfaceWithOneMethod, Class<?> resource) { Method[] resourceMethods = resourceInterfaceWithOneMethod.getMethods(); if (resourceMethods == null || resourceMethods.length != 1) { //All the interfaces should have just one method. throw new IllegalArgumentException( resourceInterfaceWithOneMethod + " should be an interface with just one method."); } Method method = ReflectionUtils.findMethod(resource, resourceMethods[0].getName(), null); return method; }