简体   繁体   English

Java泛型? 扩展Clazz

[英]Java generics ? extends Clazz

I'm using spring, hibernate and junit to setup a test class for some of my models. 我正在使用spring,hibernate和junit为我的某些模型设置测试类。

All of my models extend BaseModel 我所有的模型都扩展了BaseModel

I have the following function in my testing class: 我的测试课中有以下功能:

void printValidation(Set<ConstraintViolation<? extends BaseModel>> v){
        Iterator<ConstraintViolation<? extends BaseModel>> it = v.iterator();
        while (it.hasNext()) {
            ConstraintViolation<? extends BaseModel> violation = it.next();
            l.info("Validation error {}", violation);
        }
    }

I use it like so inside a test case: 我在测试用例中这样使用它:

eModel = new Entry(); //This class extends BaseModel
Set<ConstraintViolation<? extends BaseModel>> v = validator.validate(eModel);
assertTrue("There should be validation errors...", v.size() > 0);
printValidation(v);

However, I get the following message in Eclipse, and it does not seem to work: Type mismatch: cannot convert from Set<ConstraintViolation<Entry>> to Set<ConstraintViolation<? extends BaseModel>> 但是,我在Eclipse中收到以下消息,并且似乎不起作用:类型不匹配:无法从Set<ConstraintViolation<Entry>>转换为Set<ConstraintViolation<? extends BaseModel>> Set<ConstraintViolation<? extends BaseModel>>

I have a bunch of other tests, and if I make the function take <Entry> instead of <? extends BaseEntry> 我还有很多其他测试,如果我使函数采用<Entry>而不是<? extends BaseEntry> <? extends BaseEntry> it works. <? extends BaseEntry>起作用。 I have a number of models I'm testing like this, and it is sort of the whole point of generics to not have to duplicate this. 我有很多这样的模型正在测试,而通用类的全部要点就是不必复制它。

What am I missing here, I guess it has something to do with either what validator.validate is returning or something? 我在这里想念的是什么,我想这可能与validator.validate返回什么有关?

** Edited to fix inline code formatting ** **编辑以修复内联代码格式**

@geoand - Almost, here is the working code: @geoand-差不多,这是工作代码:

<T extends BaseModel> void printValidation(Set<ConstraintViolation<T>> v){
    Iterator<ConstraintViolation<T>> it = v.iterator();
    while (it.hasNext()) {
        ConstraintViolation<T> violation = it.next();
        l.info("Validation error {}", violation);
    }
}

And the function that does the test: 和做测试的功能:

@Test
public void testEntry() {
    Set<ConstraintViolation<Entry>> v = validator.validate(eModel);
    assertTrue("There should be validation errors...", v.size() > 0);
    printValidation(v);

尝试void <T extends BaseModel> printValidation(Set<ConstraintViolation<T>> v)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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