**
通过反射动态获取创建对象*
例:
dto
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class User {
private String name;
private String telNumber;
}
枚举类
import java.util.HashMap;
import java.util.Map;
public enum ClassPathEnum {
//path类名,name为serviceCode
USER ("dto.User", "User");
public static ClassPathEnum toE_RequestParam(String code) {
return codeMap.get(code);
}
public static String getNameByPath(String path) {
ClassPathEnum procResult = codeMap.get(path);
if (procResult != null) {
return procResult .getName();
}
return "";
}
public static String getPathByName(String name) {
ClassPathEnum procResult = nameMap.get(name);
if (procResult != null) {
return procResult.getPath();
}
return "";
}
private static Map<String, ClassPathEnum> codeMap;
private static Map<String, ClassPathEnum> nameMap;
private ClassPathEnum(String path, String name) {
this.path = path;
this.name = name;
}
static {
codeMap = new HashMap<String, ClassPathEnum>();
nameMap = new HashMap<String, ClassPathEnum>();
for ( ClassPathEnum procResult : ClassPathEnum.values()) {
codeMap.put(procResult .getPath(), procResult );
nameMap.put(procResult .getName(), procResult );
}
}
private String path;
private String name;
public boolean equals(String path) {
return this.getPath().equals(path);
}
public String getPath() {
return path;
}
public String getName() {
return name;
}
public String toString() {
return this.getPath() ;
}
}
模拟外部系统调用发送http请求,请求报文格式json字符串
/**
* 通过反射动态获取创建实体对象
*/
public class reflectTest {
public static void Invoke(String name,String json) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//通过类名创建动态的实体对象*
String dtoName = ClassPathEnum.getPathByName(name);
Object dto = JSONObject.parse(json);
Class<?> classInstance = Class.forName(dtoName);
Object obj = classInstance.newInstance();
//json字符串与实体对象转换
ObjectMapper objectMapper = new ObjectMapper();
obj = objectMapper.convertValue(dto,classInstance);
//可以在调用具体接口时先对其他服务传来的报文进行校验,写成公共校验
//之后根据接口需求,在具体的业务方法进行dto转换,进行业务处理
System.out.println("finish,debug查看obj里的属性以及值");
}
/**
* 用main方法来模拟发送json请求
*/
public static void main(String[] args) {
try {
ObjectMapper mapper = new ObjectMapper();
User user=new User();
user.setName("测试数据1");
user.setTelNumber("18833333333");
String json=mapper.writeValueAsString(user);
Invoke("User",json);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}