反射可能用于的场景

动态加载 YAML 中指定的类

**# test-config.yaml
className: com.example.TestService
method: queryData
parameters:

  • type: java.lang.String
    value: "testId"
  • type: java.lang.Integer
    value: 123**
java 复制代码
public class YamlClassLoader {
    public Object loadAndExecute(String yamlPath) throws Exception {
        // 1. 读取YAML配置
        Map<String, Object> config = loadYaml(yamlPath);
        
        // 2. 动态加载类
        String className = (String) config.get("className");
        Class<?> clazz = Class.forName(className);
        
        // 3. 创建实例
        Object instance = clazz.getDeclaredConstructor().newInstance();
        
        // 4. 获取方法
        String methodName = (String) config.get("method");
        List<Map<String, String>> params = (List<Map<String, String>>) config.get("parameters");
        
        // 5. 准备参数
        Class<?>[] paramTypes = new Class<?>[params.size()];
        Object[] paramValues = new Object[params.size()];
        for (int i = 0; i < params.size(); i++) {
            Map<String, String> param = params.get(i);
            paramTypes[i] = Class.forName(param.get("type"));
            paramValues[i] = convertValue(param.get("value"), paramTypes[i]);
        }
        
        // 6. 获取并调用方法
        Method method = clazz.getMethod(methodName, paramTypes);
        return method.invoke(instance, paramValues);
    }
    
    private Object convertValue(String value, Class<?> type) {
        if (type == String.class) return value;
        if (type == Integer.class) return Integer.parseInt(value);
        // ... 其他类型转换
        return null;
    }
}

Mock 数据注入到测试对象

java 复制代码
public class MockDataInjector {
    public void injectMockData(Object testObject, Map<String, Object> mockData) 
        throws Exception {
        
        Class<?> clazz = testObject.getClass();
        
        // 遍历所有字段
        for (Field field : clazz.getDeclaredFields()) {
            // 检查是否有需要mock的注解
            if (field.isAnnotationPresent(MockData.class)) {
                field.setAccessible(true); // 允许访问私有字段
                
                // 获取mock数据
                String fieldName = field.getName();
                Object mockValue = mockData.get(fieldName);
                
                // 注入mock数据
                field.set(testObject, mockValue);
            }
        }
    }
}

// 使用示例
@Test
public class UserServiceTest {
    @MockData
    private UserDao userDao;
    
    @BeforeTest
    public void setup() {
        // 准备mock数据
        Map<String, Object> mockData = new HashMap<>();
        mockData.put("userDao", new MockUserDao());
        
        // 注入mock数据
        new MockDataInjector().injectMockData(this, mockData);
    }
}

动态调用测试方法

java 复制代码
public class DynamicTestExecutor {
    public void executeTest(String className, String methodName) throws Exception {
        // 1. 加载测试类
        Class<?> testClass = Class.forName(className);
        Object testInstance = testClass.getDeclaredConstructor().newInstance();
        
        // 2. 查找并执行@BeforeTest方法
        for (Method method : testClass.getMethods()) {
            if (method.isAnnotationPresent(BeforeTest.class)) {
                method.invoke(testInstance);
            }
        }
        
        // 3. 执行指定的测试方法
        Method testMethod = testClass.getMethod(methodName);
        if (testMethod.isAnnotationPresent(Test.class)) {
            testMethod.invoke(testInstance);
        }
    }
}

// 使用实例
@Test
public class TestRunner {
    public void runSpecificTest() {
        DynamicTestExecutor executor = new DynamicTestExecutor();
        executor.executeTest(
            "com.example.UserServiceTest",
            "testUserCreation"
        );
    }
}

完整的工具类示例

java 复制代码
public class TestReflectionUtils {
    
    // 1. 动态加载并实例化类
    public static Object createInstance(String className) throws Exception {
        Class<?> clazz = Class.forName(className);
        return clazz.getDeclaredConstructor().newInstance();
    }
    
    // 2. 设置字段值
    public static void setField(Object object, String fieldName, Object value) 
        throws Exception {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, value);
    }
    
    // 3. 获取字段值
    public static Object getField(Object object, String fieldName) 
        throws Exception {
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        return field.get(object);
    }
    
    // 4. 调用方法
    public static Object invokeMethod(Object object, String methodName, 
        Object... args) throws Exception {
        Class<?>[] paramTypes = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++) {
            paramTypes[i] = args[i].getClass();
        }
        Method method = object.getClass().getMethod(methodName, paramTypes);
        return method.invoke(object, args);
    }
    
    // 5. 查找注解标注的方法
    public static List<Method> findAnnotatedMethods(Class<?> clazz, 
        Class<? extends Annotation> annotation) {
        List<Method> methods = new ArrayList<>();
        for (Method method : clazz.getDeclaredMethods()) {
            if (method.isAnnotationPresent(annotation)) {
                methods.add(method);
            }
        }
        return methods;
    }
}




public class TestExample {
    public static void main(String[] args) throws Exception {
        // 1. 动态加载类
        Object testInstance = TestReflectionUtils.createInstance(
            "com.example.UserServiceTest"
        );
        
        // 2. 注入mock数据
        TestReflectionUtils.setField(testInstance, "userDao", new MockUserDao());
        
        // 3. 查找并执行测试方法
        List<Method> testMethods = TestReflectionUtils.findAnnotatedMethods(
            testInstance.getClass(), 
            Test.class
        );
        
        for (Method method : testMethods) {
            TestReflectionUtils.invokeMethod(testInstance, method.getName());
        }
    }
}
相关推荐
卷无止境几秒前
FastAPI 与 RustFS 集成指南
后端·python·fastapi
青 春 记 忆3 分钟前
零基础入门python25:新增账目——Decimal、日期和输入校验
python·后端开发
北风toto4 分钟前
阿里云 MaxCompute通过python脚本调用odps流程和执行sql
python·阿里云·odps
ShineWinsu9 分钟前
对于TRAE中配置Qt的解析
开发语言·c++·ide·vscode·qt·ai·trae
qq_1611112722 分钟前
Pillow项目深度解析:Python图像处理的终极武器
图像处理·python·pillow·开源库·历史解析
梅孔立22 分钟前
Pi-Agent 终极极简配置文档(Java+Vue+Python爬虫 4-5千文件项目)
java·vue.js·python
李可以量化27 分钟前
Redis Client 从了解到精通(二)下:String 类型进阶操作全解
redis·git·python·量化交易·qmt
wy31362282127 分钟前
Git——ignore让项目的 target 目录真正被忽略(忽略其他文件也是同样的道理)
开发语言·git
格林威28 分钟前
C#图像分块处理:图像按行或按块(Tile)切分,多个 CPU 核心同时处理不同的区域
开发语言·图像处理·人工智能·机器学习·计算机视觉·c#·工业相机
leisoo809735 分钟前
财报舞弊预警系统实战用Python挖掘应收存货异常因子 IG50免费开源股票数据API接口
开发语言·python