对于反射的一些基础知识这里不再说明,网上有很多的文章了,可参考这篇文章https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html
这里主要通过一个简单的例子说明反射的应用。该例子主要是模仿mybatis的一个简单的实现,该例子可能有很多问题,但只是为了说明反射的一个具体应用。
package com.ctcf._2019;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RefrectTest {
public static void main(String[] args) throws Exception {
String resultType = "com.ctcf._2019.Cat";
List<Map<String, Object>> result = new ArrayList<>();
Map<String, Object> map = new HashMap<>();
map.put("name", "cat1");
map.put("age", 1);
result.add(map);
Cat cat = (Cat) format(result, resultType);
System.out.println(cat);
Map<String, Object> map2 = new HashMap<>();
map2.put("name", "cat2");
map2.put("age", 2);
result.add(map2);
List<Cat> list = (List<Cat>) format(result, resultType);
System.out.println(list);
}
public static Object format(List<Map<String, Object>> result, String resultType) throws Exception{
Class clz = Class.forName(resultType);
Method[] methods = clz.getDeclaredMethods();
if(result.size()>1){
List<Object> list = new ArrayList<>();
for(Map<String, Object> resultMap: result){
Object o = clz.newInstance();
for(Method method: methods){
String methodName = formatMethodName(method.getName());
if(resultMap.containsKey(methodName)){
method.invoke(o, resultMap.get(methodName));
}
}
list.add(o);
}
return list;
}else{
Object o = clz.newInstance();
Map<String, Object> resultMap = result.get(0);
for(Method method: methods){
String methodName = formatMethodName(method.getName());
if(resultMap.containsKey(methodName)){
method.invoke(o, resultMap.get(methodName));
}
}
return o;
}
}
public static String formatMethodName(String name){
if(name.startsWith("set") && name.length()>4){
return name.substring(3, 4).toLowerCase() + name.substring(4);
}else{
return name;
}
}
}
class Cat{
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Cat [name=" + name + ", age=" + age + "]";
}
}
执行结果:
Cat [name=cat1, age=1]
[Cat [name=cat1, age=1], Cat [name=cat2, age=2]]