BEST PRACTICES FOR JAVA GENERICS
what is Abstract class?
is a template definition of methods and variables in a specific class, or category of objects
is a class, but difference common class
Abstract class khác class thông thường vì:
ví dụ:
abstract class Container<T> {
T item;
Container(T item) {
this.item = item;
}
abstract void display();
}
class StringContainer extends Container<String> {
StringContainer(String item) {
super(item);
}
void display() {
System.out.println("Item: " + item);
}
}
class IntegerContainer extends Container<Integer> {
IntegerContainer(Integer item) {
super(item);
}
void display() {
System.out.println("Item: " + item);
}
}
public class Main {
public static void main(String[] args) {
Container<String> stringContainer = new StringContainer("Hello");
stringContainer.display();
Container<Integer> integerContainer = new IntegerContainer(42);
integerContainer.display();
}
}
Tình huống áp dụng trong code project
package com.nmt.ecommercespringbootbe.domain.model.mappers;
import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractModelMapper<E, D> {
protected final ModelMapper modelMapper;
private final Class<E> entityClass;
private final Class<D> dtoClass;
public AbstractModelMapper(ModelMapper modelMapper, Class<E> entityClass, Class<D> dtoClass) {
this.modelMapper = modelMapper;
this.entityClass = entityClass;
this.dtoClass = dtoClass;
}
public D toDto(E entity) {
return entity != null ? modelMapper.map(entity, dtoClass) : null;
}
public E toEntity(D dto) {
return dto != null ? modelMapper.map(dto, entityClass) : null;
}
}
Trường private final Class<E> entityClass;
trong Java thường được sử dụng thay vì private final E entityClass;
vì những lý do sau:
E
, không thể biết được kiểu thực sự của E
vào thời điểm chạy.Class<E>
là một cách để lưu trữ thông tin về kiểu E
trong thời gian chạy.Class<E>
cho phép bạn thực hiện kiểm tra kiểu động (type checking) tại thời điểm chạy, cho phép các thao tác phức tạp hơn như kiểm tra kiểu, khởi tạo động và xử lý các kiểu generics khác.Vì những lý do này, khi bạn cần lưu trữ thông tin về kiểu generics E
, thường sử dụng Class<E>
để biểu thị lớp của đối tượng E
trong thời gian chạy.