Best Assertj code snippet using org.assertj.core.util.introspection.FieldUtils.readField
Source:FieldSupport.java
...18import static java.util.stream.Collectors.toList;19import static org.assertj.core.util.ArrayWrapperList.wrap;20import static org.assertj.core.util.IterableUtil.isNullOrEmpty;21import static org.assertj.core.util.Streams.stream;22import static org.assertj.core.util.introspection.FieldUtils.readField;23import java.lang.reflect.Field;24import java.util.Collections;25import java.util.List;26import org.assertj.core.configuration.ConfigurationProvider;27import org.assertj.core.util.VisibleForTesting;28/**29 * Utility methods for fields access.30 *31 * @author Joel Costigliola32 */33public enum FieldSupport {34 EXTRACTION(true), EXTRACTION_OF_PUBLIC_FIELD_ONLY(false), COMPARISON(true);35 private static final String CHAR = "char";36 private static final String BOOLEAN = "boolean";37 private static final String DOUBLE = "double";38 private static final String FLOAT = "float";39 private static final String LONG = "long";40 private static final String INT = "int";41 private static final String SHORT = "short";42 private static final String BYTE = "byte";43 private static final String SEPARATOR = ".";44 private boolean allowUsingPrivateFields;45 /**46 * Returns the instance dedicated to extraction of fields.47 *48 * @return the instance dedicated to extraction of fields.49 */50 public static FieldSupport extraction() {51 return EXTRACTION;52 }53 /**54 * Returns the instance dedicated to comparison of fields.55 *56 * @return the instance dedicated to comparison of fields.57 */58 public static FieldSupport comparison() {59 return COMPARISON;60 }61 /**62 * Build a new {@link FieldSupport}63 *64 * @param allowUsingPrivateFields whether to read private fields or not.65 */66 FieldSupport(boolean allowUsingPrivateFields) {67 this.allowUsingPrivateFields = allowUsingPrivateFields;68 }69 @VisibleForTesting70 public boolean isAllowedToUsePrivateFields() {71 return allowUsingPrivateFields;72 }73 /**74 * Sets whether the use of private fields is allowed.75 * If a method tries to extract/compare private fields and is not allowed to, it will fail with an exception.76 *77 * @param allowUsingPrivateFields allow private fields extraction and comparison. Default {@code true}.78 */79 public void setAllowUsingPrivateFields(boolean allowUsingPrivateFields) {80 ConfigurationProvider.loadRegisteredConfiguration();81 this.allowUsingPrivateFields = allowUsingPrivateFields;82 }83 /**84 * Returns a <code>{@link List}</code> containing the values of the given field name, from the elements of the given85 * <code>{@link Iterable}</code>. If the given {@code Iterable} is empty or {@code null}, this method will return an86 * empty {@code List}. This method supports nested fields (e.g. "address.street.number").87 *88 * @param <T> the type of the extracted elements.89 * @param fieldName the name of the field. It may be a nested field. It is left to the clients to validate for90 * {@code null} or empty.91 * @param fieldClass the expected type of the given field.92 * @param target the given {@code Iterable}.93 * @return an {@code Iterable} containing the values of the given field name, from the elements of the given94 * {@code Iterable}.95 * @throws IntrospectionError if an element in the given {@code Iterable} does not have a field with a matching name.96 */97 public <T> List<T> fieldValues(String fieldName, Class<T> fieldClass, Iterable<?> target) {98 if (isNullOrEmpty(target)) return emptyList();99 if (isNestedField(fieldName)) {100 String firstFieldName = popFieldNameFrom(fieldName);101 Iterable<Object> fieldValues = fieldValues(firstFieldName, Object.class, target);102 // extract next sub-field values until reaching the last sub-field103 return fieldValues(nextFieldNameFrom(fieldName), fieldClass, fieldValues);104 }105 return simpleFieldValues(fieldName, fieldClass, target);106 }107 public List<Object> fieldValues(String fieldName, Iterable<?> target) {108 return fieldValues(fieldName, Object.class, target);109 }110 /**111 * Returns a <code>{@link List}</code> containing the values of the given field name, from the elements of the given112 * <code>{@link Iterable}</code>. If the given {@code Iterable} is empty or {@code null}, this method will return an113 * empty {@code List}. This method supports nested fields (e.g. "address.street.number").114 *115 * @param <T> the type of the extracted elements.116 * @param fieldName the name of the field. It may be a nested field. It is left to the clients to validate for117 * {@code null} or empty.118 * @param fieldClass the expected type of the given field.119 * @param target the given {@code Iterable}.120 * @return an {@code Iterable} containing the values of the given field name, from the elements of the given121 * {@code Iterable}.122 * @throws IntrospectionError if an element in the given {@code Iterable} does not have a field with a matching name.123 */124 public <T> List<T> fieldValues(String fieldName, Class<T> fieldClass, Object[] target) {125 return fieldValues(fieldName, fieldClass, wrap(target));126 }127 private <T> List<T> simpleFieldValues(String fieldName, Class<T> clazz, Iterable<?> target) {128 return stream(target).map(e -> e == null ? null : fieldValue(fieldName, clazz, e))129 .collect(collectingAndThen(toList(), Collections::unmodifiableList));130 }131 private String popFieldNameFrom(String fieldNameChain) {132 if (!isNestedField(fieldNameChain)) {133 return fieldNameChain;134 }135 return fieldNameChain.substring(0, fieldNameChain.indexOf(SEPARATOR));136 }137 private String nextFieldNameFrom(String fieldNameChain) {138 if (!isNestedField(fieldNameChain)) {139 return "";140 }141 return fieldNameChain.substring(fieldNameChain.indexOf(SEPARATOR) + 1);142 }143 /*144 * <pre><code class='java'> isNestedField("address.street"); // true145 * isNestedField("address.street.name"); // true146 * isNestedField("person"); // false147 * isNestedField(".name"); // false148 * isNestedField("person."); // false149 * isNestedField("person.name."); // false150 * isNestedField(".person.name"); // false151 * isNestedField("."); // false152 * isNestedField(""); // false</code></pre>153 */154 private boolean isNestedField(String fieldName) {155 return fieldName.contains(SEPARATOR) && !fieldName.startsWith(SEPARATOR) && !fieldName.endsWith(SEPARATOR);156 }157 /**158 * Return the value of field from a target object. The field must not be static or synthetic (since 3.19.0).159 * <p>160 * Return null if field is nested and one of the nested value is null, ex :161 * <pre><code class='java'> fieldValue(race.name, String.class, frodo); // will return null if frodo.race is null</code></pre>162 *163 * @param <T> the type of the extracted value.164 * @param fieldName the name of the field. It may be a nested field. It is left to the clients to validate for165 * {@code null} or empty.166 * @param target the given object167 * @param fieldClass type of field168 * @return the value of the given field name169 * @throws IntrospectionError if the given target does not have a field with a matching name.170 */171 public <T> T fieldValue(String fieldName, Class<T> fieldClass, Object target) {172 if (target == null) return null;173 if (isNestedField(fieldName)) {174 String outerFieldName = popFieldNameFrom(fieldName);175 Object outerFieldValue = readSimpleField(outerFieldName, Object.class, target);176 // extract next sub-field values until reaching the last sub-field177 return fieldValue(nextFieldNameFrom(fieldName), fieldClass, outerFieldValue);178 }179 return readSimpleField(fieldName, fieldClass, target);180 }181 @SuppressWarnings("unchecked")182 private <T> T readSimpleField(String fieldName, Class<T> clazz, Object target) {183 try {184 Object fieldValue = readField(target, fieldName, allowUsingPrivateFields);185 if (clazz.isPrimitive()) {186 switch (clazz.getSimpleName()) {187 case BYTE:188 Byte byteValue = (byte) fieldValue;189 return (T) byteValue;190 case SHORT:191 Short shortValue = (short) fieldValue;192 return (T) shortValue;193 case INT:194 Integer intValue = (int) fieldValue;195 return (T) intValue;196 case LONG:197 Long longValue = (long) fieldValue;198 return (T) longValue;...
Source:FieldUtils.java
...92 * @return the field value93 * @throws IllegalArgumentException if the field is null94 * @throws IllegalAccessException if the field is not accessible95 */96 private static Object readField(Field field, Object target) throws IllegalAccessException {97 return readField(field, target, false);98 }99 /**100 * Reads a Field.101 *102 * @param field the field to use103 * @param target the object to call on, may be null for static fields104 * @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.105 * @return the field value106 * @throws IllegalArgumentException if the field is null107 * @throws IllegalAccessException if the field is not made accessible108 */109 private static Object readField(Field field, Object target, boolean forceAccess) throws IllegalAccessException {110 checkArgument(field != null, "The field must not be null");111 if (forceAccess && !field.isAccessible()) {112 field.setAccessible(true);113 } else {114 MemberUtils.setAccessibleWorkaround(field);115 }116 return field.get(target);117 }118 /**119 * Reads the named field. Superclasses will be considered.120 * <p>121 * Since 3.19.0 static and synthetic fields are ignored.122 *123 * @param target the object to reflect, must not be null124 * @param fieldName the field name to obtain125 * @param forceAccess whether to break scope restrictions using the <code>setAccessible</code> method.126 * <code>False</code> will only match public fields.127 * @return the field value128 * @throws IllegalArgumentException if the class or field name is null or the field can not be found.129 * @throws IllegalAccessException if the named field is not made accessible130 */131 static Object readField(Object target, String fieldName, boolean forceAccess) throws IllegalAccessException {132 checkArgument(target != null, "target object must not be null");133 Class<?> cls = target.getClass();134 Field field = getField(cls, fieldName, forceAccess);135 checkArgument(field != null, "Cannot locate field %s on %s", fieldName, cls);136 checkArgument(!isStatic(field.getModifiers()), "Reading static field is not supported and field %s is static on %s",137 fieldName, cls);138 checkArgument(!field.isSynthetic(), "Reading synthetic field is not supported and field %s is", fieldName);139 // already forced access above, don't repeat it here:140 return readField(field, target);141 }142}...
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2import java.lang.reflect.Field;3import java.lang.reflect.InvocationTargetException;4import java.lang.reflect.Method;5import java.util.Arrays;6import java.util.List;7import java.util.stream.Collectors;8public class 1 {9 public static void main(String[] args) {10 List<String> list = Arrays.asList("a", "b", "c");11 String field = "value";12 Field f = FieldUtils.getField(list.getClass(), field, true);13 System.out.println("Field: " + f);14 try {15 Method m = FieldUtils.readField(list.getClass(), field, true);16 System.out.println("Method: " + m);17 } catch (IllegalAccessException e) {18 e.printStackTrace();19 }20 }21}22Method: public final void java.util.Arrays$ArrayList.set(int,java.lang.Object)
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2import java.lang.reflect.Field;3import java.lang.reflect.InvocationTargetException;4public class Test {5 public static void main(String[] args) {6 Field field = FieldUtils.readField("field", Test.class, true);7 System.out.println("Field value: " + field);8 }9}10import org.assertj.core.util.introspection.FieldUtils;11import java.lang.reflect.Field;12import java.lang.reflect.InvocationTargetException;13public class Test {14 public static void main(String[] args) {15 Field field = FieldUtils.readField("field", Test.class, true);16 System.out.println("Field value: " + field);17 }18}19import org.assertj.core.util.introspection.FieldUtils;20import java.lang.reflect.Field;21import java.lang.reflect.InvocationTargetException;22public class Test {23 public static void main(String[] args) {24 Field field = FieldUtils.readField("field", Test.class, true);25 System.out.println("Field value: " + field);26 }27}28import org.assertj.core.util.introspection.FieldUtils;29import java.lang.reflect.Field;30import java.lang.reflect.InvocationTargetException;31public class Test {32 public static void main(String[] args) {33 Field field = FieldUtils.readField("field", Test.class, true);34 System.out.println("Field value: " + field);35 }36}37import org.assertj.core.util.introspection.FieldUtils;38import java.lang.reflect.Field;39import java.lang.reflect.InvocationTargetException;40public class Test {41 public static void main(String[] args) {42 Field field = FieldUtils.readField("field", Test.class, true);43 System.out.println("Field value: " + field);44 }45}46import org.assertj.core.util.introspection.FieldUtils;47import java.lang.reflect.Field;48import java.lang.reflect.InvocationTargetException;49public class Test {50 public static void main(String[] args) {51 Field field = FieldUtils.readField("field", Test.class, true);52 System.out.println("Field value: " + field);53 }54}
readField
Using AI Code Generation
1package org.assertj.core.util.introspection;2import java.lang.reflect.Field;3import java.lang.reflect.InvocationTargetException;4import java.lang.reflect.Method;5import java.util.List;6import java.util.Map;7import java.util.concurrent.ConcurrentHashMap;8import org.assertj.core.util.introspection.FieldSupport;9import org.assertj.core.util.introspection.IntrospectionError;10import org.assertj.core.util.introspection.PropertyOrFieldSupport;11import org.assertj.core.util.introspection.PropertySupport;12import org.assertj.core.util.introspection.TypeSupport;13public class FieldUtils {14 private static final Map<Class<?>, FieldSupport> FIELD_SUPPORT_CACHE = new ConcurrentHashMap<Class<?>, FieldSupport>();15 private static final FieldSupport PROPERTY_SUPPORT = new PropertySupport();16 private static final FieldSupport FIELD_SUPPORT = new FieldSupport();17 private static final FieldSupport PROPERTY_OR_FIELD_SUPPORT = new PropertyOrFieldSupport();18 private static final TypeSupport TYPE_SUPPORT = new TypeSupport();19 private static final FieldUtils INSTANCE = new FieldUtils();20 public static FieldUtils instance() {21 return INSTANCE;22 }23 public static FieldSupport fieldSupport() {24 return FIELD_SUPPORT;25 }26 public static FieldSupport propertySupport() {27 return PROPERTY_SUPPORT;28 }29 public static FieldSupport propertyOrFieldSupport() {30 return PROPERTY_OR_FIELD_SUPPORT;31 }32 public static TypeSupport typeSupport() {33 return TYPE_SUPPORT;34 }35 private FieldUtils() {36 }37 public static FieldSupport getFieldSupport(Class<?> clazz) {38 FieldSupport fieldSupport = FIELD_SUPPORT_CACHE.get(clazz);39 if (fieldSupport != null) {40 return fieldSupport;41 }42 fieldSupport = new PropertyOrFieldSupport();43 FIELD_SUPPORT_CACHE.put(clazz, fieldSupport);44 return fieldSupport;45 }46 public static Object readField(Object target, String field, boolean forceAccess) {47 if (target == null) {48 throw new IntrospectionError("target object should not be null");49 }50 if (field == null) {51 throw new IntrospectionError("field name should not be null");52 }53 FieldSupport fieldSupport = getFieldSupport(target.getClass());54 return fieldSupport.read(target, field, forceAccess);55 }56 public static Object readField(Object target, String field) {57 return readField(target, field, true);58 }59 public static void writeField(Object target, String field, Object value, boolean forceAccess) {60 if (
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2import java.lang.reflect.Field;3import java.lang.reflect.InvocationTargetException;4public class Test {5 public static void main(String[] args) {6 Field field = FieldUtils.readField(Test.class, "field", true);7 System.out.println(field);8 }9}
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2public class 1 {3 public static void main(String[] args) {4 FieldUtils.readField(new Object(), "name", true);5 }6}7import org.assertj.core.util.introspection.FieldUtils;8public class 2 {9 public static void main(String[] args) {10 FieldUtils.readField(new Object(), "name", true);11 }12}13import org.assertj.core.util.introspection.FieldUtils;14public class 3 {15 public static void main(String[] args) {16 FieldUtils.readField(new Object(), "name", true);17 }18}19import org.assertj.core.util.introspection.FieldUtils;20public class 4 {21 public static void main(String[] args) {22 FieldUtils.readField(new Object(), "name", true);23 }24}25import org.assertj.core.util.introspection.FieldUtils;26public class 5 {27 public static void main(String[] args) {28 FieldUtils.readField(new Object(), "name", true);29 }30}31import org.assertj.core.util.introspection.FieldUtils;32public class 6 {33 public static void main(String[] args) {34 FieldUtils.readField(new Object(), "name", true);35 }36}37import org.assertj.core.util.introspection.FieldUtils;38public class 7 {39 public static void main(String[] args) {40 FieldUtils.readField(new Object(), "name", true);41 }42}43import org.assertj.core.util.introspection.FieldUtils;44public class 8 {45 public static void main(String
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2import java.lang.reflect.Field;3public class ReadField {4 public static void main(String[] args) {5 try {6 Field field = FieldUtils.readField("field1", "class1");7 System.out.println("Field name: " + field.getName());8 } catch (Exception e) {9 e.printStackTrace();10 }11 }12}
readField
Using AI Code Generation
1import org.assertj.core.util.introspection.FieldUtils;2public class 1 {3 public static void main(String[] args) {4 TestClass test = new TestClass();5 TestClass test2 = new TestClass();6 test.a = 1;7 test2.a = 2;8 System.out.println("Value of variable a: "+FieldUtils.readField(test, "a", true));9 System.out.println("Value of variable a: "+FieldUtils.readField(test2, "a", true));10 }11}12class TestClass {13 public int a;14}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!