How to use forEachField method of com.tngtech.jgiven.impl.util.ReflectionUtil class

Best JGiven code snippet using com.tngtech.jgiven.impl.util.ReflectionUtil.forEachField

Source:ReflectionUtil.java Github

copy

Full Screen

...25 /**26 * Iterates over all fields of the given class and all its super classes27 * and calls action.act() for the fields that are annotated with the given annotation.28 */29 public static void forEachField( final Object object, Class<?> clazz, final FieldPredicate predicate, final FieldAction action ){30 forEachSuperClass( clazz, clazzAction -> {31 for( Field field : clazzAction.getDeclaredFields() ) {32 if( predicate.isTrue( field ) ) {33 action.act( object, field );34 }35 }36 } );37 }38 /**39 * Iterates over all methods of the given class and all its super classes40 * and calls action.act() for the methods that are annotated with the given annotation.41 */42 public static void forEachMethod( final Object object, Class<?> clazz, final Class<? extends Annotation> annotation,43 final MethodAction action ){44 forEachSuperClass( clazz, clazzAction -> {45 for( Method method : clazzAction.getDeclaredMethods() ) {46 if( method.isAnnotationPresent( annotation ) ) {47 action.act( object, method );48 }49 }50 } );51 }52 /**53 * Iterates over all super classes of the given class (including the class itself)54 * and calls action.act() for these classes.55 */56 public static void forEachSuperClass( Class<?> clazz, ClassAction action ){57 try {58 action.act( clazz );59 Class<?> superclass = clazz.getSuperclass();60 if( superclass != null ) {61 forEachSuperClass( superclass, action );62 }63 } catch( Exception e ) {64 throw Throwables.propagate( e );65 }66 }67 public static FieldPredicate hasAtLeastOneAnnotation( final Class<? extends Annotation>... annotation ){68 return field -> {69 for( Class<? extends Annotation> clazz : annotation ) {70 if( field.isAnnotationPresent( clazz ) ) {71 return true;72 }73 }74 return false;75 };76 }77 public static FieldPredicate allFields(){78 return field -> true;79 }80 public static FieldPredicate nonStaticField(){81 return field -> !Modifier.isStatic( field.getModifiers() );82 }83 public static boolean hasConstructor( Class<?> type, Class<?>... parameterTypes ){84 try {85 type.getDeclaredConstructor( parameterTypes );86 return true;87 } catch( NoSuchMethodException e ) {88 return false;89 }90 }91 public interface FieldPredicate {92 boolean isTrue( Field field ) throws Exception;93 }94 public interface ClassAction {95 void act( Class<?> clazz ) throws Exception;96 }97 public interface FieldAction {98 void act( Object object, Field field ) throws Exception;99 }100 public interface MethodAction {101 void act( Object object, Method method ) throws Exception;102 }103 public static Optional<Method> findMethodTransitively( Class<?> clazz, String methodName ){104 if( clazz == null ) {105 return Optional.empty();106 }107 try {108 return Optional.of( clazz.getDeclaredMethod( methodName ) );109 } catch( NoSuchMethodException e ) {110 return findMethodTransitively( clazz.getSuperclass(), methodName );111 }112 }113 public static <T> T newInstance( Class<T> type ){114 return newInstance( type, new Class<?>[0] );115 }116 public static <T> T newInstance( Class<T> type, Class<?>[] parameterTypes, Object... parameterValues ){117 try {118 Constructor<T> constructor = type.getDeclaredConstructor( parameterTypes );119 constructor.setAccessible( true );120 return constructor.newInstance( parameterValues );121 } catch( InstantiationException e ) {122 throw new RuntimeException( e );123 } catch( IllegalAccessException e ) {124 throw new RuntimeException( e );125 } catch( NoSuchMethodException e ) {126 throw new RuntimeException( e );127 } catch( InvocationTargetException e ) {128 throw new RuntimeException( e );129 }130 }131 public static void invokeMethod( Object object, Method method, String errorDescription ){132 log.debug( "Executing method %s of class %s", method, object.getClass() );133 makeAccessible( method, errorDescription );134 try {135 method.invoke( object );136 } catch( IllegalArgumentException e ) {137 log.debug( "Caught exception:", e );138 throw new JGivenExecutionException( "Could not execute " + toReadableString( method ) + errorDescription +139 ", because it requires parameters. " + "Remove the parameters and try again.", e );140 } catch( IllegalAccessException e ) {141 log.debug( "Caught exception:", e );142 throw new JGivenExecutionException( "Could not execute " + toReadableString( method ) + errorDescription +143 ", because of insuffient access rights. "144 + "Either make the method public or disable your security manager while executing JGiven tests.", e );145 } catch( InvocationTargetException e ) {146 throw new JGivenUserException( method, errorDescription, e.getCause() );147 }148 }149 /**150 * Returns a {@link List} of objects reflecting all the non-static field values declared by the class or interface151 * represented by the given {@link Class} object and defined by the given {@link Object}. This includes152 * {@code public}, {@code protected}, default (package) access, and {@code private} fields, but excludes inherited153 * fields. The elements in the {@link List} returned are not sorted and are not in any particular order. This method154 * returns an empty {@link List} if the class or interface declares no fields, or if the given {@link Class} object155 * represents a primitive type, an array class, or void.156 *157 * @param clazz class or interface declaring fields158 * @param target instance of given {@code clazz} from which field values should be retrieved159 * @param errorDescription customizable part of logged error message160 * @return a {@link List} containing all the found field values (never {@code null})161 */162 public static List<Object> getAllNonStaticFieldValuesFrom( final Class<?> clazz, final Object target, final String errorDescription ){163 return getAllFieldValues( target, getAllNonStaticFields( clazz ), errorDescription );164 }165 private static Function<Field, Object> getFieldValueFunction( final Object target, final String errorDescription ){166 return field -> getFieldValueOrNull( field, target, errorDescription );167 }168 public static Object getFieldValueOrNull( String fieldName, Object target, String errorDescription ){169 try {170 Field field = target.getClass().getDeclaredField( fieldName );171 return getFieldValueOrNull( field, target, errorDescription );172 } catch( Exception e ) {173 log.warn(174 format( "Not able to access field '%s'." + errorDescription, fieldName ), e );175 return null;176 }177 }178 public static Object getFieldValueOrNull( Field field, Object target, String errorDescription ){179 makeAccessible( field, "" );180 try {181 return field.get( target );182 } catch( IllegalAccessException e ) {183 log.warn(184 format( "Not able to access field '%s'." + errorDescription, toReadableString( field ) ), e );185 return null;186 }187 }188 public static List<Field> getAllNonStaticFields( Class<?> clazz ){189 final List<Field> result = Lists.newArrayList();190 forEachField( null, clazz, nonStaticField(), new FieldAction() {191 @Override192 public void act( Object target, Field field ) throws Exception{193 result.add( field );194 }195 } );196 return result;197 }198 public static List<Object> getAllFieldValues( Object target, Iterable<Field> fields, String errorDescription ){199 return StreamSupport.stream( fields.spliterator(), false )200 .map( getFieldValueFunction( target, errorDescription ) )201 .collect( Collectors.toList() );202 }203 public static List<String> getAllFieldNames( Iterable<Field> fields ){204 return StreamSupport.stream( fields.spliterator(), false )...

Full Screen

Full Screen

Source:FieldCache.java Github

copy

Full Screen

...28 List<Class<? extends Annotation>> annotationList = ImmutableList.copyOf( scenarioStageClasses );29 List<Field> fields = fieldMap.get( annotationList );30 if( fields == null ) {31 final List<Field> newFields = Lists.newArrayList();32 ReflectionUtil.forEachField( null, clazz,33 ReflectionUtil.hasAtLeastOneAnnotation( scenarioStageClasses ),34 new ReflectionUtil.FieldAction() {35 @Override36 public void act( Object object, Field field ) throws Exception {37 field.setAccessible( true );38 newFields.add( field );39 }40 }41 );42 fieldMap.put( annotationList, newFields );43 return newFields;44 }45 return fields;46 }...

Full Screen

Full Screen

forEachField

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.impl.util.ReflectionUtil;2import java.lang.reflect.Field;3import java.util.List;4public class Test {5 public static void main(String[] args) {6 List<Field> fields = ReflectionUtil.forEachField(Test.class, field -> {7 return true;8 });9 System.out.println(fields);10 }11}

Full Screen

Full Screen

forEachField

Using AI Code Generation

copy

Full Screen

1import com.tngtech.jgiven.impl.util.ReflectionUtil;2import com.tngtech.jgiven.report.model.*;3import java.lang.reflect.Field;4import java.util.List;5import java.util.stream.Collectors;6import java.util.stream.Stream;7public class Test {8 public static void main(String[] args) {9 ReportModel reportModel = new ReportModel();10 reportModel.setScenarios(new ScenarioModel());11 reportModel.getScenarios().setSteps(new StepModel());12 reportModel.getScenarios().getSteps().setAttachments(new AttachmentModel());13 reportModel.getScenarios().getSteps().getAttachments().setFile(new FileModel());14 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileName("File Name");15 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileContent("File Content");16 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileExtension("File Extension");17 reportModel.getScenarios().getSteps().setAttachments(new AttachmentModel());18 reportModel.getScenarios().getSteps().getAttachments().setFile(new FileModel());19 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileName("File Name");20 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileContent("File Content");21 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileExtension("File Extension");22 reportModel.getScenarios().getSteps().setAttachments(new AttachmentModel());23 reportModel.getScenarios().getSteps().getAttachments().setFile(new FileModel());24 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileName("File Name");25 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileContent("File Content");26 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileExtension("File Extension");27 reportModel.getScenarios().getSteps().setAttachments(new AttachmentModel());28 reportModel.getScenarios().getSteps().getAttachments().setFile(new FileModel());29 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileName("File Name");30 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileContent("File Content");31 reportModel.getScenarios().getSteps().getAttachments().getFile().setFileExtension("File Extension");

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful