All the fields of a class are accessible via the Class.getDeclaredFields() method. This method returns an array of Field:
Field[] fields = clazz.getDeclaredFields();
// final java.lang.Object modern.challenge.Pair.left
// final java.lang.Object modern.challenge.Pair.right
System.out.println("Fields: " + Arrays.toString(fields));
For fetching the actual name of the fields, we can easily provide a helper method:
public static List<String> getFieldNames(Field[] fields) {
return Arrays.stream(fields)
.map(Field::getName)
.collect(Collectors.toList());
}
Now, we only receive the names of the fields:
List<String> fieldsName = getFieldNames(fields);
// left, right
System.out.println("Fields names: " + fieldsName);
Getting the value of a field can be done via a general method named Object get(Object obj) and via a set of getFoo() methods (consider documentation for details). The obj represents a static or instance field. For example, let's assume the ProcedureOutputs class that have has a private field named callableStatement which is of type CallableStatement. Let's use Field.get() method to access this field for checking if the CallableStatement is closed:
ProcedureOutputs procedureOutputs
= storedProcedure.unwrap(ProcedureOutputs.class);
Field csField = procedureOutputs.getClass()
.getDeclaredField("callableStatement");
csField.setAccessible(true);
CallableStatement cs
= (CallableStatement) csField.get(procedureOutputs);
System.out.println("Is closed? " + cs.isClosed());
For fetching only the public fields, call getFields(). For searching for a certain field, call getField​(String fieldName) or getDeclaredField​(String name).