Java 如何获得列表的通用类型,或者如果不可能,如何解决提供的任务?

Java 如何获得列表的通用类型,或者如果不可能,如何解决提供的任务?,java,generics,reflection,Java,Generics,Reflection,任务是:要求您在一家生产和包装面包房的公司中创建质量控制系统,主要类别的片段如下: // 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&

任务是:要求您在一家生产和包装面包房的公司中创建质量控制系统,主要类别的片段如下:

// 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
  }

}
//这些及其子类应该通过质量检查
类面包店{}
类蛋糕扩展面包房{}
//这个和其他东西不应该
课堂论文{}
//这些箱子是用来装东西的
接口盒{
无效认沽权(T项);
T get();
}
//你需要学习的课程
类质量控制{

公共静态布尔检查(列表首先检查null,然后检查空。 您可以使用instanceof检查类型:

class QualityControl {
    public static <T> boolean check(java.util.List<T> items) {
        if (items == null || items.isEmpty()) {
            return false;
        }
        return items.stream()
               .noneMatch(b -> (!(b instanceof Box)) 
                          || !(((Box) b).get() instanceof Bakery));
    }
}
类质量控制{
公共静态布尔检查(java.util.List项){
if(items==null | | items.isEmpty()){
返回false;
}
returnitems.stream()
.noneMatch(b->(!(b盒实例))
||!((框)b.get()面包店实例));
}
}

这是一些非常复杂且相当无用的代码。我怀疑你是从某人那里复制了“答案”?“当列表为空时,我有麻烦”-什么问题?你在方法的第一行检查这种情况。也许你说的是
NullPointerException
?我很确定你应该使用
instanceof
来检查列表的内容。即使上面的代码起作用,这也是错误的方法。虽然赋值是还有点令人困惑,因为
check
方法的通用参数阻止您传递不包含烘焙框的列表(因此对于不包含框的列表,您不能返回false,因为这将是编译时错误).代码没有被复制,它可以工作。但如果我有面包店的盒子列表,它是空的,我就不能返回真的。可能这真的是没用的代码,但老实说,我现在找不到其他任何东西。即使盒子不是空的,也没有帮助。对不起,一切都很好,可以工作。非常感谢:)
class QualityControl {
    public static <T> boolean check(java.util.List<T> items) {
        if (items == null || items.isEmpty()) {
            return false;
        }
        return items.stream()
               .noneMatch(b -> (!(b instanceof Box)) 
                          || !(((Box) b).get() instanceof Bakery));
    }
}