如何创建将泛型作为参数并从中调用方法的方法?

时间:2018-07-05 15:12:41

标签: java

我有一个mixin,我想将其用于几种类型的请求,例如CatRequest和DogRequest。我在mixin中创建了一个方法,该方法根据请求的类型和响应中的设置从请求中检索某些详细信息。检查实例并像下面这样强制转换是否是理想的选择?还是有更好的方法使用泛型来处理此问题?

default <T> Response setAnimalDetails(final T request, final Response response) {
    Animal animal = new Animal();
    if (request instanceof CatRequest) {
        CatRequest catRequest = (CatRequest) request;
        animal.setType(catRequest.getType());
        animal.setAge(catRequest.getAge());
        animal.setWhiskerLength(catRequest.getWhiskerLength());
    } else if (request instanceof DogRequest) {
        DogRequest dogRequest = (DogRequest) request;
        animal.setType(dogRequest.getAnimalType());
        animal.setAge(dogRequest.getAge());
        // since dogs don't have whiskers, DogRequest doesn't have a whiskers field
    }
    response.setAnimal(animal);
    return response;
}

1 个答案:

答案 0 :(得分:1)

Mixin和泛型似乎是一种通过继承来实现某些目的的inherit回方式。

interface AnimalMaker {
    Animal createAnimal();
}

class CatRequest implements AnimalMaker {
    @Override 
    public Animal createAnimal() {
        Animal animal = new Animal();
        animal.setType(getType());
        animal.setAge(getAge());
        animal.setWhiskerLength(getWhiskerLength());
        return animal;
    }
}

class DogRequest implements AnimalMaker {
    @Override 
    public Animal createAnimal() {
        Animal animal = new Animal();
        animal.setType(getAnimalType());
        animal.setAge(getAge());
        return animal;
    }
}

这样,您无需使用setAnimalDetails方法,只需将您的请求声明为AnimalMaker并执行

response.setAnimal(request.createAnimal());

最好制作Animal之类的CatDog之类,并为请求类键入参数,但是您可以自己做。< / p>