反射小实例

package com.smart.practice1.models;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

public class ReflectTest {
public static void main(String[] arg) throws Exception { SysRoleInfo sysRoleInfo=init(); } public static SysRoleInfo init() throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //通过类装载器获取类对象 ClassLoader loader=Thread.currentThread().getContextClassLoader(); Class clazz=loader.loadClass("com.smart.practice1.models.SysRoleInfo"); //获取类的默认构造器对象并通过实例化 Constructor constructor=clazz.getDeclaredConstructor((Class[]) null); SysRoleInfo sysRoleInfo= (SysRoleInfo) constructor.newInstance(); //通过反射方法设置属性值 Method setUuid=clazz.getMethod("setUuid",String.class); setUuid.invoke(sysRoleInfo, UUID.randomUUID()); return sysRoleInfo; } }

 

上一篇:mybatis关联映射一对多


下一篇:mybatis抽取基类BaseMapper