List of usage examples for java.lang.reflect Method getModifiers
@Override public int getModifiers()
From source file:de.matzefratze123.heavyspleef.core.flag.FlagRegistry.java
public void registerFlag(Class<? extends AbstractFlag<?>> clazz) { Validate.notNull(clazz, "clazz cannot be null"); Validate.isTrue(!registeredFlagsMap.containsValue(clazz), "Cannot register flag twice"); /* Check if the class provides the required Flag annotation */ Validate.isTrue(clazz.isAnnotationPresent(Flag.class), "Flag-Class must be annotated with the @Flag annotation"); Flag flagAnnotation = clazz.getAnnotation(Flag.class); String name = flagAnnotation.name(); Validate.isTrue(!name.isEmpty(),// w w w. j a va 2s. c o m "name() of annotation of flag for class " + clazz.getCanonicalName() + " cannot be empty"); /* Generate a path */ StringBuilder pathBuilder = new StringBuilder(); Flag parentFlagData = flagAnnotation; do { pathBuilder.insert(0, parentFlagData.name()); Class<? extends AbstractFlag<?>> parentFlagClass = parentFlagData.parent(); parentFlagData = parentFlagClass.getAnnotation(Flag.class); if (parentFlagData != null && parentFlagClass != NullFlag.class) { pathBuilder.insert(0, FLAG_PATH_SEPERATOR); } } while (parentFlagData != null); String path = pathBuilder.toString(); /* Check for name collides */ for (String flagPath : registeredFlagsMap.primaryKeySet()) { if (flagPath.equalsIgnoreCase(path)) { throw new IllegalArgumentException( "Flag " + clazz.getName() + " collides with " + registeredFlagsMap.get(flagPath).getName()); } } /* Check if the class can be instantiated */ try { Constructor<? extends AbstractFlag<?>> constructor = clazz.getDeclaredConstructor(); //Make the constructor accessible for future uses constructor.setAccessible(true); } catch (NoSuchMethodException | SecurityException e) { throw new IllegalArgumentException("Flag-Class must provide an empty constructor"); } HookManager hookManager = heavySpleef.getHookManager(); boolean allHooksPresent = true; for (HookReference ref : flagAnnotation.depend()) { if (!hookManager.getHook(ref).isProvided()) { allHooksPresent = false; } } if (allHooksPresent) { for (Method method : clazz.getDeclaredMethods()) { if (!method.isAnnotationPresent(FlagInit.class)) { continue; } if ((method.getModifiers() & Modifier.STATIC) == 0) { throw new IllegalArgumentException("Flag initialization method " + method.getName() + " in type " + clazz.getCanonicalName() + " is not declared as static"); } queuedInitMethods.add(method); } if (flagAnnotation.hasCommands()) { CommandManager manager = heavySpleef.getCommandManager(); manager.registerSpleefCommands(clazz); } } registeredFlagsMap.put(path, flagAnnotation, clazz); }
From source file:com.all.app.BeanStatisticsWriter.java
private List<CSVColumn> auto(Object object) { List<CSVColumn> columns = new ArrayList<CSVColumn>(); Method[] declaredMethods = object.getClass().getDeclaredMethods(); for (Method method : declaredMethods) { boolean noArguments = method.getParameterTypes().length == 0; boolean isVoid = method.getReturnType().equals(void.class); boolean isPublic = (method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC; boolean isNotStatic = (method.getModifiers() & Modifier.STATIC) != Modifier.STATIC; boolean isGetter = method.getName().startsWith("get"); if (isGetter && noArguments && isPublic && isNotStatic && !isVoid) { columns.add(new CSVColumnMethodReflected(method.getName(), method.getName())); }/* www .ja v a 2 s.c o m*/ } return columns; }
From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java
private void processMethod(Method method) { if (method.isSynthetic()) { return;/*w w w . j a v a2 s. co m*/ } if (!Modifier.isPublic(method.getModifiers())) { return; } if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) { if (method.getParameterTypes().length == 0) { String name = method.getName(); if (name.indexOf('$') == -1) { if (name.length() > 3 && name.startsWith("get") && Character.isUpperCase(name.charAt(3))) { name = name.substring(3); } else if (name.length() > 2 && name.startsWith("is") && Character.isUpperCase(name.charAt(2)) && (method.getReturnType() == Boolean.class || method.getReturnType() == boolean.class)) { name = name.substring(2); } PropertyFetcher fetcher = new GetterPropertyFetcher(method, true); List<PropertyFetcher> propertyFetchers = staticFetchers.get(name); if (propertyFetchers == null) { staticFetchers.put(name, propertyFetchers = new ArrayList<PropertyFetcher>()); } propertyFetchers.add(fetcher); String decapitalized = Introspector.decapitalize(name); if (!decapitalized.equals(name)) { propertyFetchers = staticFetchers.get(decapitalized); if (propertyFetchers == null) { staticFetchers.put(decapitalized, propertyFetchers = new ArrayList<PropertyFetcher>()); } propertyFetchers.add(fetcher); } } } } }
From source file:com.all.app.DefaultContext.java
private void checkInvokePredestroy(Method method, Object ob) { boolean annotationPresent = false; boolean noArguments = method.getParameterTypes().length == 0; boolean isVoid = method.getReturnType().equals(void.class); boolean isPublic = (method.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC; boolean isNotStatic = (method.getModifiers() & Modifier.STATIC) != Modifier.STATIC; Annotation[] annotations = method.getAnnotations(); for (Annotation annotation : annotations) { if (annotation.getClass().getName().contains("PreDestroy") || annotation.toString().contains("PreDestroy")) { annotationPresent = true;/*from w ww . ja va 2s.c om*/ } } if (annotationPresent && noArguments && isPublic && isNotStatic && isVoid) { try { method.invoke(ob); } catch (Exception e) { log.error(e, e); } } }
From source file:com.amalto.core.metadata.ClassRepository.java
private TypeMetadata loadClass(Class clazz) { String typeName = getTypeName(clazz); if (getType(typeName) != null) { // If already defined return it. return getType(typeName); } else if (getNonInstantiableType(StringUtils.EMPTY, typeName) != null) { return getNonInstantiableType(StringUtils.EMPTY, typeName); }//from w w w . j a v a 2s . c om entityToJavaClass.put(typeName, clazz); if (Map.class.isAssignableFrom(clazz)) { return MAP_TYPE; } if (ArrayListHolder.class.equals(clazz)) { typeName = typeName + listCounter++; } boolean isEntity = typeStack.isEmpty(); ComplexTypeMetadata classType = new ComplexTypeMetadataImpl(StringUtils.EMPTY, typeName, isEntity); addTypeMetadata(classType); typeStack.push(classType); String keyFieldName = ""; //$NON-NLS-1$ if (isEntity && ObjectPOJO.class.isAssignableFrom(clazz)) { SimpleTypeFieldMetadata keyField = new SimpleTypeFieldMetadata(typeStack.peek(), true, false, true, "unique-id", //$NON-NLS-1$ STRING, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY); keyField.setData(LINK, "PK/unique-id"); //$NON-NLS-1$ classType.addField(keyField); } else if (isEntity) { keyFieldName = "unique-id"; //$NON-NLS-1$ } // Class is abstract / interface: load sub classes if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())) { Iterable<Class> subClasses = getSubclasses(clazz); ComplexTypeMetadata superType = typeStack.peek(); if (superType.isInstantiable()) { typeStack.clear(); } for (Class subClass : subClasses) { TypeMetadata typeMetadata = loadClass(subClass); typeMetadata.setInstantiable(superType.isInstantiable()); typeMetadata.addSuperType(superType); } if (superType.isInstantiable()) { typeStack.push(superType); } } // Analyze methods Method[] classMethods = getMethods(clazz); for (Method declaredMethod : classMethods) { if (!Modifier.isStatic(declaredMethod.getModifiers())) { if (isBeanMethod(declaredMethod) && isClassMethod(clazz, declaredMethod)) { String fieldName = getName(declaredMethod); if (typeStack.peek().hasField(fieldName)) { continue; // TODO Avoid override of fields (like PK) } Class<?> returnType = declaredMethod.getReturnType(); FieldMetadata newField; boolean isMany = false; boolean isKey = keyFieldName.equals(fieldName); if (Iterable.class.isAssignableFrom(returnType)) { returnType = listItemType != null ? listItemType : getListItemClass(declaredMethod, returnType); listItemType = null; isMany = true; } else if (ArrayListHolder.class.isAssignableFrom(returnType)) { listItemType = getListItemClass(declaredMethod, returnType); isMany = false; } else if (Map.class.isAssignableFrom(returnType)) { isMany = true; } else if (returnType.isArray()) { isMany = true; returnType = ((Class) returnType.getComponentType()); } else if (returnType.getName().startsWith("org.w3c.")) { //$NON-NLS-1$ // TODO Serialized XML to string column continue; } else if (Class.class.equals(returnType)) { continue; } else if (returnType.getPackage() != null && returnType.getPackage().getName().startsWith("java.io")) { //$NON-NLS-1$ continue; } if (returnType.isPrimitive() || returnType.getName().startsWith(JAVA_LANG_PREFIX)) { String fieldTypeName = returnType.getName().toLowerCase(); if (fieldTypeName.startsWith(JAVA_LANG_PREFIX)) { fieldTypeName = StringUtils.substringAfter(fieldTypeName, JAVA_LANG_PREFIX); } TypeMetadata fieldType; if (Types.BYTE.equals(fieldTypeName) && isMany) { fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.BASE64_BINARY); } else { fieldType = new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, fieldTypeName); } newField = new SimpleTypeFieldMetadata(typeStack.peek(), isKey, isMany, isKey, fieldName, fieldType, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY); LongString annotation = declaredMethod.getAnnotation(LongString.class); if (Types.STRING.equals(fieldTypeName) && annotation != null) { fieldType.setData(MetadataRepository.DATA_MAX_LENGTH, String.valueOf(Integer.MAX_VALUE)); if (annotation.preferLongVarchar()) { fieldType.setData(LongString.PREFER_LONGVARCHAR, Boolean.TRUE); } } } else { ComplexTypeMetadata fieldType; if (Map.class.isAssignableFrom(returnType)) { fieldType = MAP_TYPE; } else { fieldType = (ComplexTypeMetadata) loadClass(returnType); } if (!isEntity || !fieldType.isInstantiable()) { newField = new ContainedTypeFieldMetadata(typeStack.peek(), isMany, false, fieldName, new SoftTypeRef(this, StringUtils.EMPTY, fieldType.getName(), false), Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY); } else { newField = new ReferenceFieldMetadata(typeStack.peek(), false, isMany, false, fieldName, fieldType, fieldType.getField("unique-id"), //$NON-NLS-1$ Collections.<FieldMetadata>emptyList(), StringUtils.EMPTY, true, false, STRING, Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY, StringUtils.EMPTY); } } typeStack.peek().addField(newField); } } } typeStack.peek().addField(new SimpleTypeFieldMetadata(typeStack.peek(), false, false, false, "digest", //$NON-NLS-1$ new SimpleTypeMetadata(XMLConstants.W3C_XML_SCHEMA_NS_URI, Types.STRING), Collections.<String>emptyList(), Collections.<String>emptyList(), Collections.<String>emptyList(), StringUtils.EMPTY)); return typeStack.pop(); }
From source file:com.strandls.alchemy.rest.client.AlchemyRestClientFactory.java
/** * Get an instance of a rest proxy instance for the service class. * * @param serviceClass/*from w w w . j av a 2s. com*/ * the service class. * @return the proxy implementation that invokes the remote service. * @throws Exception */ @SuppressWarnings("unchecked") public <T> T getInstance(@NonNull final Class<T> serviceClass) throws Exception { final ProxyFactory factory = new ProxyFactory(); if (serviceClass.isInterface()) { factory.setInterfaces(new Class[] { serviceClass }); } else { factory.setSuperclass(serviceClass); } factory.setFilter(new MethodFilter() { @Override public boolean isHandled(final Method method) { return Modifier.isPublic(method.getModifiers()); } }); final Class<?> klass = factory.createClass(); final Object instance = objenesis.getInstantiatorOf(klass).newInstance(); ((ProxyObject) instance).setHandler(new RestMethodInvocationHandler(baseUri, clientProvider, interfaceAnalyzer.analyze(serviceClass), responseToThrowableMapper, builderFilter)); return (T) instance; }
From source file:com.alibaba.dubbo.config.spring.AnnotationBean.java
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (!isMatchPackage(bean)) { return bean; }/*from w w w. j a va 2 s. c om*/ Method[] methods = bean.getClass().getMethods(); for (Method method : methods) { String name = method.getName(); if (name.length() > 3 && name.startsWith("set") && method.getParameterTypes().length == 1 && Modifier.isPublic(method.getModifiers()) && !Modifier.isStatic(method.getModifiers())) { try { Reference reference = method.getAnnotation(Reference.class); if (reference != null) { Object value = refer(reference, method.getParameterTypes()[0]); if (value != null) { method.invoke(bean, new Object[] {}); } } } catch (Throwable e) { logger.error("Failed to init remote service reference at method " + name + " in class " + bean.getClass().getName() + ", cause: " + e.getMessage(), e); } } } Field[] fields = bean.getClass().getDeclaredFields(); for (Field field : fields) { try { if (!field.isAccessible()) { field.setAccessible(true); } Reference reference = field.getAnnotation(Reference.class); if (reference != null) { Object value = refer(reference, field.getType()); if (value != null) { field.set(bean, value); } } } catch (Throwable e) { logger.error("Failed to init remote service reference at filed " + field.getName() + " in class " + bean.getClass().getName() + ", cause: " + e.getMessage(), e); } } return bean; }
From source file:io.ingenieux.lambada.maven.ServeMojo.java
public void loadPathHandlers() throws Exception { final Set<Method> methodsAnnotatedWith = extractRuntimeAnnotations(ApiGateway.class); getLog().info("There are " + methodsAnnotatedWith.size() + " found methods."); for (Method m : methodsAnnotatedWith) { ApiGateway a = m.getAnnotation(ApiGateway.class); PathHandler pathHandler = new PathHandler(); pathHandler.setPath(a.path());/*from w w w .j ava 2s . co m*/ pathHandler.setMethod(m); boolean bStatic = Modifier.isStatic(m.getModifiers()); // TODO: ApiGateway getLog().info("Class: " + m.getDeclaringClass().getName()); if (!bStatic) { try { pathHandler.setInstance(m.getDeclaringClass().newInstance()); } catch (Exception exc) { throw new RuntimeException("Unable to create class " + m.getDeclaringClass(), exc); } } pathHandler.setMethodType(a.method()); getLog().info("Added path handler: " + pathHandler); pathHandlers.add(pathHandler.build()); } }
From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java
private TypeConverterHolder buildTypeConverterFromConverterAnnotatedClass(final Class<?> type, final Method method) throws IllegalArgumentException { ensureConverterMethodIsValid(type, method); this.log.trace("Building TypeConverter from method [{}] ...", method); final TypeConverter typeConverter; final Class<?> fromType = method.getParameterTypes()[0]; final Class<?> toType = method.getReturnType(); if (isStatic(method.getModifiers())) { typeConverter = new StaticMethodTypeConverter(method); } else {/*from ww w . ja va 2 s .co m*/ typeConverter = new CdiInstanceMethodTypeConverter(new CdiInjector(this.beanManager), method, this.typeConverterRegistry); } this.log.trace("Built TypeConverter [{}]", typeConverter, method); return TypeConverterHolder.newNonFallbackTypeConverterHolder(fromType, toType, typeConverter); }
From source file:com.tmall.wireless.tangram.support.SimpleClickSupport.java
private void findClickMethods(Method[] methods) { for (Method method : methods) { String methodName = method.getName(); if (!methodName.equals(ON_CLICK_METHOD_NAME) && methodName.startsWith(ON_CLICK_METHOD_NAME) || (methodName.startsWith(ON_CLICK_METHOD_PREFIX) && methodName.endsWith(ON_CLICK_METHOD_POSTFIX))) { int modifiers = method.getModifiers(); if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 3 || parameterTypes.length == 4) { Class<?> viewType = parameterTypes[0]; Class<?> cellType = parameterTypes[1]; Class<?> clickIntType = parameterTypes[2]; if (View.class.isAssignableFrom(viewType) && BaseCell.class.isAssignableFrom(cellType) && (clickIntType.equals(int.class) || clickIntType.equals(Integer.class))) { if (parameterTypes.length == 4) { Class<?> clickParamsType = parameterTypes[3]; if (Map.class.isAssignableFrom(clickParamsType)) { mOnClickMethods.put(viewType, new OnClickMethod(4, method)); }//from w ww . j a v a 2 s . c om } else { mOnClickMethods.put(viewType, new OnClickMethod(3, method)); } } } } } } }