1. 实体类
@Data
public class Person {
private Long id; private String name;
}
2. SQL
<select id="getNameById" resultType="com.entity.Person"> select name from person where id =#{id} </select>
3. 简说
1. 现在 SQL 查询 了字段 name
2. 那么首先会通过反射调用name的set方法,如果属性没有set方法,则会直接反射对属性赋值
3. 模拟代码
1 public static Object doSetInvoke(String column, Object columnValue) throws Exception { 2 String prefix = "set"; 3 Class<?> clazz = Class.forName("com.entity.Person"); 4 5 Object instance = clazz.newInstance();
6 try { // 反射调用调用属性的 set方法 7 Method columnSetMethod = clazz.getDeclaredMethod(prefix + column.substring(0, 1).toUpperCase() + column.substring(1), columnValue.getClass()); 8 columnSetMethod.setAccessible(true); 9 columnSetMethod.invoke(instance, columnValue); 10 } catch (NoSuchMethodException e1) { // 当属性无set方法时, 直接反射给属性赋值 11 try { 12 Field field = clazz.getDeclaredField(column); 13 System.out.println("field"); 14 field.setAccessible(true); 15 field.set(instance, columnValue); 16 } catch (NoSuchFieldException e2) { 17 return instance; 18 } 19 } 20 return instance; 21 }
浙公网安备 33010602011771号