lundi 9 septembre 2019

How to get generic type of list or if it is impossible how to solve provided task?

Task is: You are asked to create quality control system in a company that produces and packs Bakery, the snippet of main classes follows:

// These and its subclasses should pass quality check
class Bakery {}

class Cake extends Bakery {}

// And this and other stuff should not
class Paper {}

// These boxes are used to pack stuff
interface Box<T> {
    void put(T item);
    T get();
}

// Class you need to work on
class QualityControl {

  public static boolean check(List<Box<? extends Bakery>> boxes) {
      // Add implementation here
  }

}

Implement check method in a way it would:

Return true if all objects in all boxes belong to class Bakery or its subclasses or list contains no boxes.

Return false otherwise, including cases when Box is empty or List contains something that is not Box at all.

The method shouldn't throw any exceptions.

I tried this, but I have troubles when list is empty and my solution does not seem like preferred one.

class QualityControl {

    public static<T> boolean check(java.util.List<T> items) {

        if (items.isEmpty()) return true;
        if (items == null) return false;
        boolean areBoxes = true;

        java.util.Set<String> ss = new java.util.HashSet<>();

        //Check if all are boxes
        for (T item : items) {
            java.util.Set<java.lang.reflect.Type> set = new java.util.HashSet<>();
            boolean isBox = false;
            Class c = item.getClass();
            while (c != null) {
                for (java.lang.reflect.Type type : c.getGenericInterfaces()) set.add(type);
                c = c.getSuperclass();
            }

            for (java.lang.reflect.Type type : set) {
                String boxName = Box.class.getName();
                String typeName = type.getTypeName();
                if (typeName.startsWith(boxName + "<")) {
                    isBox = true;
                    ss.add(typeName);
                    break;
                }
            }

            areBoxes &= isBox;
        }

        if (!areBoxes) return false;

        //Check if box contain bakery

        boolean isIns = true;

        for (String s : ss) {
            s = s.substring(4);
            s = s.substring(0, s.length() - 1);
            boolean helper = false;
            try {
                Class clazz = Class.forName(s);

                while (clazz != null) {
                    if (clazz.equals(Bakery.class)) {
                        helper = true;
                        break;
                    }
                    clazz = clazz.getSuperclass();
                }
                isIns &= helper;
                helper = false;

            } catch (ClassNotFoundException e) {
                return false;
            }

        }

        return isIns;
    }

} 





Aucun commentaire:

Enregistrer un commentaire