java—有没有其他方法可以重用representationmodelassemblersupport

flseospp  于 2021-06-29  发布在  Java
关注(0)|答案(0)|浏览(302)

与每个 Model 类我必须创建一个 RepresentationModelAssemblerSupport 类,这有点多余,所以我写了一个泛型 RepresentationModelAssemblerSupport 班级。
泛型representationmodelassemblersupport类:

public class ModelAssembler<T, E extends RepresentationModel<E>> extends RepresentationModelAssemblerSupport<T, E> {
    private final Class<E> model;
    public ModelAssembler(Class<?> controllerClass, Class<E> resourceType) {
        super(controllerClass, resourceType);
        model = resourceType;
    }
    @Override
    protected E instantiateModel(T entity) {
        try {
            Constructor<E> constructor = model.getConstructor(entity.getClass());
            return constructor.newInstance(entity);
        } catch (NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }

    @Override
    public E toModel(T entity) {
        Class<?> clazz = entity.getClass();
        try {
            Method method = clazz.getMethod("getId");
            Object id = method.invoke(entity);
            return createModelWithId(id, entity);
        } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
            throw new RuntimeException("lỗi server");
        }
    }
}

它可以工作,但我必须使用java反射,这可能会导致性能问题 toModel 每次请求都会被呼叫。
有没有其他方法可以概括 RepresentationModelAssemblerSupport ?
下面是model类的一个示例:

@Relation(collectionRelation = "products", itemRelation = "product")
@Getter
public class ProductModel extends RepresentationModel<ProductModel> {
    private final UUID id;
    private final String name;
    private final Integer price;
    private final String description;
    public ProductModel(Product product) {
        this.id = product.getId();
        this.name = product.getName();
        this.price = product.getPrice();
        this.description = product.getDescription();
        add(linkTo(methodOn(ProductController.class).getProductColors(product.getId())).withRel("productColors"));
        add(linkTo(methodOn(ProductController.class).getProductTags(product.getId())).withRel("productTags"));
        add(linkTo(methodOn(ThumbnailController.class).getThumbnail(product.getThumbnail().getId())).withRel("thumbnail"));
        add(linkTo(methodOn(ProductController.class).all(0, new PagedResourcesAssembler<>(null, null))).withRel("all"));
    }
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题