This repository has been archived on 2021-12-05. You can view files and clone it, but cannot push or open issues or pull requests.
envoy/client/src/main/java/envoy/client/util/ReflectionUtil.java

75 lines
2.8 KiB
Java

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