private void parseResouce(){ ReflectionUtils.doWithFields(clz, new FieldCallback(){ @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if(field.getAnnotation(Id.class) != null){ idField = field; return; } Index index = null; if(null != (index = field.getAnnotation(Index.class))){ if(index.unique()){ uniqueIndexFields.add(field); }else{ nonUniqueIndexFields.add(field); } } Autowired auto = field.getAnnotation(Autowired.class); if(null != auto && auto.required()){ autowiredFields.add(field); } } }); }
/** * 解析对象为Model * 自定义filter * @param obj * @param parseSuper 是否解析父类 * @return */ public static List<Model> parseByObject(Object obj,boolean parseSuper,FieldFilter ff){ List<Model> list = new ArrayList<>(); if (obj==null) { return list; } //解析Field FieldCallback fc = new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (ff != null && !ff.matches(field)) { return; } Model m = parseByField(obj, field); if (m!=null) { list.add(m); } } }; if (parseSuper) { ReflectionUtil.doWithFields(obj.getClass(),fc); }else{ ReflectionUtil.doWithLocalFields(obj.getClass(),fc); } return list; }
private boolean determineDeleteInBatchSupported(final Class<?> genericType) { final MutableBoolean deleteInBatchSupported = new MutableBoolean(true); Reflections.doWithFields(genericType, new FieldCallback() { @Override public void doWith(final Field field) { if (!deleteInBatchSupported.getValue()) { return; } else if (Reflections.getAnnotation(field, ElementCollection.class) != null) { //element collections are mapped as separate tables, thus the values would cause a foreign key constraint violation deleteInBatchSupported.setValue(false); } else if (Reflections.getAnnotation(field, Embedded.class) != null) { //check embedded types for the same constraints if (!determineDeleteInBatchSupported(field.getType())) { deleteInBatchSupported.setValue(false); } } } }); return deleteInBatchSupported.getValue(); }
@Override public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException { // 处理DbCacheService属性 ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { processDbCacheService(bean, beanName, field); } }); // 处理EntityLoadEventListener接口 processEntityLoadEventListener(bean); // 处理IndexChangeListener接口 processIndexChangeListener(bean); return super.postProcessAfterInitialization(bean, beanName); }
public DynamoDBHashAndRangeKeyExtractingEntityMetadataImpl(final Class<T> domainType) { super(domainType); this.hashAndRangeKeyMethodExtractor = new DynamoDBHashAndRangeKeyMethodExtractorImpl<T>(getJavaType()); ReflectionUtils.doWithMethods(domainType, new MethodCallback() { public void doWith(Method method) { if (method.getAnnotation(DynamoDBHashKey.class) != null) { String setterMethodName = toSetterMethodNameFromAccessorMethod(method); if (setterMethodName != null) { hashKeySetterMethod = ReflectionUtils.findMethod(domainType, setterMethodName, method.getReturnType()); } } } }); ReflectionUtils.doWithFields(domainType, new FieldCallback() { public void doWith(Field field) { if (field.getAnnotation(DynamoDBHashKey.class) != null) { hashKeyField = ReflectionUtils.findField(domainType, field.getName()); } } }); Assert.isTrue(hashKeySetterMethod != null || hashKeyField != null, "Unable to find hash key field or setter method on " + domainType + "!"); Assert.isTrue(hashKeySetterMethod == null || hashKeyField == null, "Found both hash key field and setter method on " + domainType + "!"); }
@SuppressWarnings("unchecked") public JdbcEntityInformation(Class<T> domainClass) { super(domainClass); className = domainClass.getName(); ReflectionUtils.doWithFields(domainClass, new FieldCallback() { public void doWith(Field field) { if (field.isAnnotationPresent(ID_ANNOTATION)) { JdbcEntityInformation.this.idFields.add(field); return; } } }); if (domainClass.isAnnotationPresent(ID_CLASS_ANNOTATION)) { idType = (Class<ID>) domainClass.getAnnotation(ID_CLASS_ANNOTATION).value(); Assert.notNull(idType, "@IdClass must have a valid class"); getIdStrategy = new GetIdCompound(); } else { assertUniqueId( "There must be one and only one field annotated with @Id unless you annotate the class with @IdClass"); idType = (Class<ID>) idFields.get(0).getType(); idFields.get(0).setAccessible(true); getIdStrategy = new GetIdSingleKey(); } entityType = calculateEntityType(domainClass, idFields); }
@Override public PropertyValues postProcessPropertyValues(PropertyValues pvs, PropertyDescriptor[] pds, final Object bean, String beanName) throws BeansException { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { postProcessField(bean, field); } }); return pvs; }
public void parse(Class<?> source) { parseElement(source); ReflectionUtils.doWithFields(source, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { parseElement(field); } }); }
public void initFields(final Object testInstance, final ObjectFactory<M> marshaller) { Assert.notNull(testInstance, "TestInstance must not be null"); Assert.notNull(marshaller, "Marshaller must not be null"); ReflectionUtils.doWithFields(testInstance.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { doWithField(field, testInstance, marshaller); } }); }
public static String dumpObjectFieldsSizeEstimate(final Serializable o) { final StringBuilder sb = new StringBuilder(); sb.append(o).append(": ").append(estimateObjectSize(o)).append("\n"); ReflectionUtils.doWithFields(o.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { int mods = field.getModifiers(); if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) { return; } if (Modifier.isTransient(mods)) { return; } field.setAccessible(true); sb.append("\n"); DebugUtil.indentDebugDump(sb, 1); sb.append(field.getName()); if (Modifier.isStatic(mods)) { sb.append(" (static)"); } sb.append(": "); Object value = field.get(o); if (value == null) { sb.append("null"); } else if (value instanceof Serializable) { sb.append(estimateObjectSize((Serializable)value)); } else { sb.append("non-serializable ("+value.getClass()+")"); } } }); return sb.toString(); }
/** * * @param source * @param targetClass * @param depth * @param dtoToEntity * @return */ protected Object map(final Object source, final Class<?> targetClass, final int depth, final boolean dtoToEntity) { if (source == null) { return null; } try { final Object toRet = targetClass.newInstance(); ReflectionUtils.doWithFields(source.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalAccessException { mapField(source, targetClass, depth, dtoToEntity, toRet, field); } }, ReflectionUtils.COPYABLE_FIELDS); return toRet; } catch (Exception e) { throw new KarakuRuntimeException( String.format("Can't copy from %s to %s", source.getClass(), targetClass), e); } }
/** 构造方法 */ public ResourceDefinition(Class<?> clz, FormatDefinition format) { this.clz = clz; this.format = format.getType(); this.location = format.getLocation(); ReflectionUtility.doWithDeclaredFields(clz, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { InjectDefinition definition = new InjectDefinition(field); injects.add(definition); } }, INJECT_FILTER); }
@Override public Set<String> getIndexRangeKeyPropertyNames() { final Set<String> propertyNames = new HashSet<String>(); ReflectionUtils.doWithMethods(getJavaType(), new MethodCallback() { public void doWith(Method method) { if (method.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && method .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) || (method.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && method .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForAccessorMethod(method)); } } } }); ReflectionUtils.doWithFields(getJavaType(), new FieldCallback() { public void doWith(Field field) { if (field.getAnnotation(DynamoDBIndexRangeKey.class) != null) { if ((field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName() != null && field .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexName().trim().length() > 0) || (field.getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames() != null && field .getAnnotation(DynamoDBIndexRangeKey.class).localSecondaryIndexNames().length > 0)) { propertyNames.add(getPropertyNameForField(field)); } } } }); return propertyNames; }
/** * Creates a new {@link FieldAndGetterReflectionEntityInformation} inspecting the * given domain class for a getter carrying the given annotation. * * @param domainClass * must not be {@literal null}. * @param annotation * must not be {@literal null}. */ public FieldAndGetterReflectionEntityInformation(Class<T> domainClass, final Class<? extends Annotation> annotation) { super(domainClass); Assert.notNull(annotation); ReflectionUtils.doWithMethods(domainClass, new MethodCallback() { public void doWith(Method method) { if (method.getAnnotation(annotation) != null) { FieldAndGetterReflectionEntityInformation.this.method = method; return; } } }); if (method == null) { ReflectionUtils.doWithFields(domainClass, new FieldCallback() { public void doWith(Field field) { if (field.getAnnotation(annotation) != null) { FieldAndGetterReflectionEntityInformation.this.field = field; return; } } }); } Assert.isTrue(this.method != null || this.field != null, String.format("No field or method annotated with %s found!", annotation.toString())); Assert.isTrue(this.method == null || this.field == null, String.format("Both field and method annotated with %s found!", annotation.toString())); if (method != null) { ReflectionUtils.makeAccessible(method); } }
/** * Find annotated elements on types * @param ann annotation to search * @param clazz class to search on. * @return List with annotated elements */ public static List<AnnotatedElement> findAnnotatedElements(final Class<? extends Annotation> annotationType, Class<?> clazz) { final ArrayList<AnnotatedElement> elements = new ArrayList<AnnotatedElement>(); // Lookup fields ReflectionUtils.doWithFields(clazz, new FieldCallback() { @Override public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { if (field.getAnnotation(annotationType) != null) { elements.add(field); } } }); // Lookup methods ReflectionUtils.doWithMethods(clazz, new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { if (org.springframework.core.annotation.AnnotationUtils.getAnnotation(method, annotationType) != null) elements.add(method); } }); return elements; }
@PostConstruct protected void initializeKnownElements() { final Builder<String, List<WebElement>> builder = ImmutableMap.builder(); ReflectionUtils.doWithFields(getClass(), new FieldCallback() { @Override @SuppressWarnings("unchecked") public void doWith(final Field field) throws IllegalArgumentException, IllegalAccessException { final String name = lowerCase(join(splitByCharacterTypeCamelCase(field.getName()), ' ')); field.setAccessible(true); final Object value = ReflectionUtils.getField(field, GenericPage.this); if (value instanceof List) { builder.put(name, (List<WebElement>) value); } else if (value instanceof WebElement) { builder.put(name, Collections.singletonList((WebElement) value)); } } }, new AnnotationFieldFilter(FindBy.class)); knownElements = builder.build(); }
private CacheConfig createCacheConfig(final Class<?> clz) { CacheConfig cacheConfig = CacheConfig.valueOf(clz); final Map<String, ValueGetter<?>> indexes = new HashMap<String, ValueGetter<?>>(); // 解析注解 ReflectionUtils.doWithFields(clz, new FieldCallback() { public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { // 忽略静态属性和临时属性 if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()) || field.isAnnotationPresent(javax.persistence.Transient.class)) { return; } // 处理索引注解 if (field.isAnnotationPresent(org.hibernate.annotations.Index.class) || field.isAnnotationPresent(dbcache.anno.Index.class)) { org.hibernate.annotations.Index indexAno = field.getAnnotation(org.hibernate.annotations.Index.class); String indexName; if (indexAno != null) { indexName = indexAno.name(); } else { dbcache.anno.Index indexAno1 = field.getAnnotation(dbcache.anno.Index.class); indexName = indexAno1.name(); } try { indexes.put(indexName, AsmAccessHelper.createFieldGetter(field.getName(), clz, field)); } catch (Exception e) { logger.error("获取实体配置出错:生成索引失败(" + clz.getName() + "." + field.getName() + ")."); e.printStackTrace(); } } } }); cacheConfig.setIndexes(indexes); cacheConfig.setFieldCount(clz.getDeclaredFields().length); return cacheConfig; }
/** * Intercepta un bean especifico. * * <p> * Intercepta todos los campos de un objeto, buscando aquellos que tengan * algún interceptor definido. * </p> * <p> * Reglas: * <ol> * <li>Si el item es un atributo normal, invocar a su respectivo * interceptor. * </p> * <li>Si es una colección, y tiene tiene la anotación {@link OneToMany}, y * su {@link CascadeType} es {@link CascadeType#ALL}, entonces se propaga la * intercepción a los miembros de la colección. </p> * * @param op * Operación actual. * @param bean * objeto que esta siendo interceptado. */ public void intercept(@Nonnull final Operation op, final Object bean) { ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() { @Override public void doWith(Field field) throws IllegalAccessException { InterceptorHandler.this.intercept(op, notNull(field), bean); } }); }