如何在静态上下文中使用泛型类与特定对象?

Cyr*_* N. 10 java inheritance static playframework-2.0

我会尽力解释.

我使用Play Framework 2,我会做很多CRUD操作.他们中有些人会identitcal,所以我想吻和DRY所以起初我在想包含一个抽象类list,details,create,updatedelete方法,与通用对象,并通过指定要使用哪个对象扩展这个类(型号和表格):

public abstract class CrudController extends Controller {
    protected static Model.Finder<Long, Model> finder = null;
    protected static Form<Model> form = null;

    public static Result list() {
        // some code here
    }

    public static Result details(Long id) {
        // some code here
    }

    public static Result create() {
        // some code here
    }

    public static Result update(Long id) {
        // some code here
    }

    public static Result delete(Long id) {
        // some code here
    }
}
Run Code Online (Sandbox Code Playgroud)

还有一个将使用CRUD的类:

public class Cities extends CrudController {
    protected static Model.Finder<Long, City> finder = City.find;
    protected static Form<City> form = form(City.class);

    // I can override a method in order to change it's behavior :
    public static Result list() {
        // some different code here, like adding some where condition
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我不在静态环境中,这将起作用.

但既然如此,我该怎么办?

Jul*_*Foy 13

这可以使用委托来实现:定义包含CRUD动作逻辑的常规Java类:

public class Crud<T extends Model> {

    private final Model.Finder<Long, T> find;
    private final Form<T> form;

    public Crud(Model.Finder<Long, T> find, Form<T> form) {
        this.find = find;
        this.form = form;
    }

    public Result list() {
        return ok(Json.toJson(find.all()));
    }

    public Result create() {
        Form<T> createForm = form.bindFromRequest();
        if (createForm.hasErrors()) {
            return badRequest();
        } else {
            createForm.get().save();
            return ok();
        }
    }

    public Result read(Long id) {
        T t = find.byId(id);
        if (t == null) {
            return notFound();
        }
        return ok(Json.toJson(t));
    }

    // … same for update and delete
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以定义一个Play控制器,其静态字段包含以下实例Crud<City>:

public class Cities extends Controller {
    public final static Crud<City> crud = new Crud<City>(City.find, form(City.class));
}
Run Code Online (Sandbox Code Playgroud)

而且你差不多完成了:你只需要为Crud动作定义路线:

GET     /                     controllers.Cities.crud.list()
POST    /                     controllers.Cities.crud.create()
GET     /:id                  controllers.Cities.crud.read(id: Long)
Run Code Online (Sandbox Code Playgroud)

注意:此示例为brevety生成JSON响应,但可以呈现HTML模板.但是,由于Play 2模板是静态类型的,因此您需要将所有这些模板作为Crud类的参数传递.