TypeParameterResolver是Mybatis的泛型参数解析器。
它的功能是什么?帮助Mybatis推断出属性、返回值、输入参数中泛型的具体类型。
它对外提供了三个方法:
resolveFieldType:解析属性的泛型;
resolveParamTypes:解析方法参数的泛型;
resolveReturnType:解析方法返回值的泛型。
示例:
package com.xncoding.pos.common.dao.entity;
import java.util.List;
public class Person<T1,T2,T3> {
public T3 t3;
public List<? extends T3> getInfo(T1 t1, T2 t2){
return null;
}
}
package com.xncoding.pos.common.dao.entity;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Student extends Person<String,Map<String,Integer>,Integer> {
@Override
public List<Integer> getInfo(String s, Map<String, Integer> map) {
return new ArrayList<>(super.t3);
}
}
package com.xncoding.pos;
import com.xncoding.pos.common.dao.entity.Person;
import com.xncoding.pos.common.dao.entity.Student;
import org.apache.ibatis.reflection.TypeParameterResolver;
import org.junit.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.lang.reflect.Type;
@SpringBootTest
public class TestTypeParameterResolver {
@Test
public void testReturnType() throws NoSuchMethodException {
Type returnType = TypeParameterResolver.resolveReturnType(Person.class.getMethods()[0], Student.class);
System.out.println("Student类中getInfo方法的返回值类型:"+returnType);
}
@Test
public void testParamType() throws NoSuchMethodException{
Type[] paramTypes = TypeParameterResolver.resolveParamTypes(Person.class.getMethods()[0], Student.class);
for (Type paramType : paramTypes) {
System.out.println("Student类中getInfo方法的各参数类型:"+paramType);
}
}
@Test
public void testFieldType()throws NoSuchFieldException{
Type str = TypeParameterResolver.resolveFieldType(Person.class.getDeclaredField("t3"), Student.class);
System.out.println("Student类中super.t4属性的类型:"+str);
}
}