Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fr.tse.fise2.info4.lab11;
- import java.lang.reflect.Field;
- import java.util.ArrayList;
- import java.util.Arrays;
- import java.util.HashSet;
- import java.util.List;
- import java.util.Set;
- /**
- * Utilities for introspection
- *
- * @author Julien Subercaze
- *
- */
- @SuppressWarnings("rawtypes")
- public class ReflectionUtils {
- public static Set<Class> getClassesFromCollection(List<Object> collec) {
- Set<Class> clazzes = new HashSet<>();
- for (Object obj : collec) {
- clazzes.add(obj.getClass());
- }
- return clazzes;
- //@formatter:off
- // return collec
- // .stream()
- // .map(obj -> obj.getClass())
- // .collect(Collectors.toSet());
- //@formatter:on
- }
- /**
- *
- * @param clazz
- * @return TODO
- */
- public static List<Field> listFields(Class clazz) {
- List<Field> myFields = new ArrayList<>();
- while (clazz != null) {
- Field[] fields = clazz.getDeclaredFields();
- for (Field field : fields) {
- myFields.add(field);
- }
- // @formatter:off
- // Arrays.asList(clazz.getDeclaredFields())
- // .stream()
- // .forEach(f -> myFields.add(f));
- // @formatter:on
- clazz = clazz.getSuperclass();
- }
- return myFields;
- }
- public static void main(String[] args) {
- Car c1 = new Car("peugeot", "205", "2E 234 42", 1997);
- Car c2 = new Car("citroen", "c4", "DF 2ZA 69", 2001);
- Plane p1 = new Plane("Airbus", "A320", "AF3456", 2004);
- Plane p2 = new Plane("Boeing", "B747", "DL345T56", 2006);
- List<Object> objects = new ArrayList<>();
- objects.add(c1);
- objects.add(c2);
- objects.add(p1);
- objects.add(p2);
- Set<Class> clazzes = ReflectionUtils.getClassesFromCollection(objects);
- for (Class cls : clazzes) {
- System.out.println("Class " + cls + " has fields : ");
- for (Field f : listFields(cls)) {
- System.out.println(f);
- }
- }
- // @formatter:off
- /*ReflectionUtils
- .getClassesFromCollection(objects)
- .stream()
- .forEach(cls -> {
- System.out.println("Class " + cls + " has fields : ");
- listFields(cls)
- .stream()
- .forEach(f -> System.out.println(f));
- });*/
- // @formatter:on
- }
- }
Add Comment
Please, Sign In to add comment