bak.struct_util.btl Maven / Gradle / Ivy
The newest version!
package ${packageName};
import org.artifact.core.lang.DTO;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Supplier;
import ${packageName}.structs.*;
public class StructUtil {
static final int STRUCT_CODE = 183928832;
static Map> cahce = new HashMap<>();
static Map codes = new HashMap<>();
static {
<%
for(struct in structs){
var hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
%>
// ${struct.remark}
cahce.put(${hashCode},() -> new ${struct.structName}());
<%}%>
<%
for(struct in structs){
hashCode = HashUtil.javaDefaultHash(struct.structName)+"";
%>
// ${struct.remark}
codes.put(${packageName}.structs.${struct.structName}.class,${hashCode});
<%}%>
}
public static T create(int code){
return (T) cahce.get(code).get();
}
public static Integer structCode(Class structClass){
return codes.get(structClass);
}
// 尝试编码
public static T tryEncoder(Object obj) {
if (obj instanceof DTO) {
if (codes.containsKey(obj.getClass())) {
int structCode = StructUtil.structCode(obj.getClass());
Map dict = new HashMap();
dict.put(STRUCT_CODE, structCode);
return (T)((DTO) obj).toMap(dict);
}
}
return (T)obj;
}
// 尝试解码
public static T tryDecoder(Object obj) {
if (obj instanceof Map) {
Map map = (Map) obj;
if (map.containsKey(STRUCT_CODE)) {
int structCode = (int) map.get(STRUCT_CODE);
if (cahce.containsKey(structCode)) {
DTO dto = StructUtil.create(structCode);
return (T)dto.forMap(map);
}
}
}
return (T)obj;
}
}