package envoy.client.util;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javafx.scene.Node;
/**
* Project: envoy-client
* File: ReflectionUtil.java
* Created: 02.08.2020
*
* @author Leon Hofmeister
* @since Envoy Client v0.2-beta
*/
public class ReflectionUtil {
private ReflectionUtil() {}
/**
* Gets all declared variables of the given instance that have the specified
* class
* (i.e. can get all {@code JComponents} (Swing) or {@code Nodes} (JavaFX) in a
* GUI class).
*
* Important: If you are using a module, you first need to declare
* "opens {your_package} to envoy.client.util;" in your module-info.java.
*
* @param the type of the object
* @param the type to return
* @param instance the instance of a given class whose values are to be
* evaluated
* @param typeToReturn the type of variable to return
* @return all variables in the given instance that have the requested type
* @throws RuntimeException if an exception occurs
* @since Envoy Client v0.2-beta
*/
public static Stream getAllDeclaredVariablesOfTypeAsStream(T instance, Class typeToReturn) {
return Arrays.stream(instance.getClass().getDeclaredFields()).filter(field -> typeToReturn.isAssignableFrom(field.getType())).map(field -> {
try {
field.setAccessible(true);
final var value = field.get(instance);
return value;
} catch (IllegalArgumentException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}).map(typeToReturn::cast);// field ->
// typeToReturn.isAssignableFrom(field.getClass())).map(typeToReturn::cast);
}
/**
* Gets all declared variables of the given instance that are children of
* {@code Node}.
*
* Important: If you are using a module, you first need to declare
* "opens {your_package} to envoy.client.util;" in your module-info.java.
*
* @param the type of the instance
* @param instance the instance of a given class whose values are to be
* evaluated
* @return all variables of the given object that have the requested type as
* {@code Stream}
* @since Envoy Client v0.2-beta
*/
public static Stream getAllDeclaredNodeVariablesAsStream(T instance) {
return getAllDeclaredVariablesOfTypeAsStream(instance, Node.class);
}
/**
* Gets all declared variables of the given instance that are children of
* {@code Node}
*
* Important: If you are using a module, you first need to declare
* "opens {your_package} to envoy.client.util;" in your module-info.java.
*
* @param the type of the instance
* @param instance the instance of a given class whose values are to be
* evaluated
* @return all variables of the given object that have the requested type
* @since Envoy Client v0.2-beta
*/
public static List getAllDeclaredNodeVariables(T instance) {
return getAllDeclaredNodeVariablesAsStream(instance).collect(Collectors.toList());
}
}