反射——根据get返回类型set值

Java反射设置默认空值
Method[] methods = bbMsg.getClass().getMethods();
for (Method method : methods) {
String methodName = method.getName();
if (methodName.startsWith("get") && !"getDestinationTemplate".equals(methodName)) {
if (method.getReturnType() == String.class && CollectionUtils.isNotEmpty(getNullValueSet())) {
setDefaultNullString(bbMsg, method, methodName);
}


}
}


private void setDefaultNullString(IPBBRefDataBO bbMsg, Method method, String methodName) {
try {
String getValue = (String) method.invoke(bbMsg);
if (getNullValueSet().contains(getValue)) {
setDefaultNullString(bbMsg, methodName);
}
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
LOGGER.warn("fail to call method " + methodName + ", message:" + bbMsg.toString());
}
}


private void setDefaultNullString(IPBBRefDataBO bbMsg, String methodName) {
String setmethodName = methodName.replace("get", "set");
try {
bbMsg.getClass().getMethod(setmethodName, String.class).invoke(bbMsg, new Object[] { null });
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException e) {
LOGGER.warn("fail to call method " + methodName + ", message:" + bbMsg.toString());
}
}
### TypeScript中的反射机制 TypeScript本身并不原生支持完整的反射机制,但它可以通过装饰器(Decorator)以及第三方库来实现部分反射功能。以下是关于TypeScript中反射的相关知识点: #### 装饰器的基础 装饰器是一种特殊类型的声明,可以附加到类声明、方法、访问符、属性或参数上。它们通过@expression的形式应用,在运行时会被执行并返回一个函数[^1]。 ```typescript function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) { const originalMethod = descriptor.value; descriptor.value = function (...args: any[]) { console.log(`Calling "${propertyKey}" with`, args); return originalMethod.apply(this, args); }; } class Greeter { greeting: string; constructor(message: string) { this.greeting = message; } @log greet(name: string): void { console.log(`${this.greeting}, ${name}`); } } ``` 在这个例子中,`@log`是一个装饰器,它记录了每次调用`greet`方法的日志信息[^2]。 #### 使用 `reflect-metadata` 实现反射 为了在TypeScript中实现更复杂的反射操作,通常会依赖于`reflect-metadata`库。这个库提供了元数据的支持,并允许开发者查询这些元数据。 ##### 安装和配置 首先需要安装`reflect-metadata`包: ```bash npm install reflect-metadata --save ``` 接着在入口文件顶部引入该模块以启用其特性: ```typescript import 'reflect-metadata'; ``` ##### 基本使用案例 下面展示了一个简单的注入服务的例子,其中利用了`Reflect.getMetadata`来读取类型定义的信息。 ```typescript // Define metadata keys. const INJECTABLE_KEY = Symbol('injectable'); // Decorator factory for marking classes as injectables. function Injectable(): ClassDecorator { return (target: Function) => Reflect.defineMetadata(INJECTABLE_KEY, true, target); } // Example service class marked as injectable. @Injectable() class MyService {} // A consumer class which will receive injected instances of services. class Consumer { public myService!: MyService; constructor() { // Inject instance based on type annotation. const serviceInstance = Reflect.construct(MyService, []); this.myService = serviceInstance; } } ``` 这里展示了如何创建自定义的`Injectable`装饰器并通过`Reflect.metadata`设置元数据标记某个类为可注入的服务[^3]。 #### 类型注册与实例化 类似于某些框架的做法,我们可以构建自己的DI(Dependency Injection)容器或者类型管理系统。这涉及到几个核心概念: - **type_info**: 存储有关类型的名称及其构造函数等细节的数据结构; - **type_index**: 提供一种方式去唯一标识每一个已知类型以便快速查找对应的`type_info`; - 将所有的此类映射存入某种形式的关系数据库表单之中——在这里我们可能只是简单地采用JavaScript的对象字面量作为我们的“表格”。 当请求特定类型的实例时,则依据给定的索引来检索相应的描述信息,并据此调用来生成新的实体对象[^4]。 ```typescript interface TypeInfo<T> { typeName: string, ctor: new(...args: any[]) => T } let registry: Map<number, TypeInfo<any>> = new Map(); function registerClass<T>(index: number, info: TypeInfo<T>) { registry.set(index, info); } function createInstance<T>(index: number): T | null { let entry = registry.get(index); if (!entry) return null; try { return new entry.ctor(); } catch(e){ throw Error(`Failed to instantiate class at index ${index}: `, e.message); } } ``` 以上代码片段演示了一种基本的设计模式,即先登记各个可用组件的具体制造说明(也就是所谓的工厂),之后再按需生产具体的产品实例。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值