简体   繁体   中英

How to cope with type erasure?

The task is You are asked to perform security audit in a company that bakes Bakery and different subclasses of it and sells it in a nice boxes. Before release to customer all boxes are checked with carefully designed NaiveQualityControl class. Numerous cases when something other than Bakery (eg Paper) was packed in Boxes and escaped the quality check happened recently.

Short look at NaiveQualityControl leads to conclusion that it's quite easy to provide NaiveQualityControl with Box filled with Paper that will pass QC, and you task is to demonstrate this. Code of related classes follows:

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


class Cake extends Bakery {}


/* But this should not */
class Paper {}

You need to add implementation to Violator.defraud() method that will do the following:

Create List of Boxes according to method signature Put Paper object in at least one Box in the list The resulting list should pass NaiveQualityControl check

I tried following

class Violator {

public static List<Box<? extends Bakery>> defraud() {
    List<Box<? extends Bakery>> lbc = new ArrayList<Box<? extends Bakery>>();
    Box<? extends Bakery> bb =lbc.get(0);
    Paper p = new Paper();
    bb.put(p);
    return lbc;
}

} But there is compilation error on line bb.put(p). I tried also to but Bakery or Cake variable and also got compilation error. So I am confused.

I wrote

public static List<Box<? extends Bakery>> defraud()   {
    List<Box<? extends Bakery>> lbc = new ArrayList<Box<? extends Bakery>>();
    Paper p = new Paper();
    try {
        Box box = Box.class.newInstance();

        box.put(p);
        lbc.add(box);
    }
    catch(IllegalAccessException iae){}
    catch(InstantiationException ie){}
    return lbc;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM