com.tngtech.jgiven.impl.util.FieldCache Maven / Gradle / Ivy
package com.tngtech.jgiven.impl.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* Cache to avoid multiple expensive reflection-based look-ups
* @since 0.7.1
*/
public class FieldCache {
private static final ConcurrentHashMap, FieldCache> instances = new ConcurrentHashMap, FieldCache>();
public static FieldCache get( Class> clazz ) {
FieldCache fieldCache = instances.get( clazz );
if( fieldCache == null ) {
fieldCache = new FieldCache( clazz );
instances.put( clazz, fieldCache );
}
return fieldCache;
}
private final Class> clazz;
private final ConcurrentHashMap>, List> fieldMap = new ConcurrentHashMap>, List>();
public FieldCache( Class> clazz ) {
this.clazz = clazz;
}
public List getFieldsWithAnnotation( final Class extends Annotation>... scenarioStageClasses ) {
List> annotationList = ImmutableList.copyOf( scenarioStageClasses );
List fields = fieldMap.get( annotationList );
if( fields == null ) {
final List newFields = Lists.newArrayList();
ReflectionUtil.forEachField( null, clazz,
ReflectionUtil.hasAtLeastOneAnnotation( scenarioStageClasses ),
new ReflectionUtil.FieldAction() {
@Override
public void act( Object object, Field field ) throws Exception {
field.setAccessible( true );
newFields.add( field );
}
}
);
fieldMap.put( annotationList, newFields );
return newFields;
}
return fields;
}
}