动态地将数组项映射到 java.reflect.Field 对象
我需要编写代码来模拟在运行时类中具有用户定义数量的可用字段。这个想法是能够将指向这些“动态”字段的 java.reflect.Field 对象返回给客户端代码。
class DynamicFieldClass {
/**
* fieldNames is the list of names of the fields we want to "exist" in the class
* they will all be of the same type (say String)
*/
public DynamicFieldClass(List<String> fieldNames) {
// ... what do we do here
}
public Field getFieldObjectFor(String desiredFieldName) {
// ... what do we do here
}
}
有没有类似于 DynamicProxy 的东西(但是对于字段)? 谢谢
I need to write code that simulates having a user-defined number of fields available in a class at runtime. The idea being to be able to return java.reflect.Field objects pointing to those "dynamic" fields to client-code.
class DynamicFieldClass {
/**
* fieldNames is the list of names of the fields we want to "exist" in the class
* they will all be of the same type (say String)
*/
public DynamicFieldClass(List<String> fieldNames) {
// ... what do we do here
}
public Field getFieldObjectFor(String desiredFieldName) {
// ... what do we do here
}
}
Is there something similar to DynamicProxy (but for fields)?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终使用 Javassist 来:
- 在运行时创建一个继承自原始类的新类定义
- 将我需要的字段注入新的类定义中
我还用静态工厂方法替换了公共构造函数,该方法生成并返回新类定义的实例。总而言之,代码如下所示:
}
I ended up using Javassist to :
- create a new class definition at runtime that inherits from my original class
- inject the fields I needed into the new class definition
I also replaced the public constructor by a static factory method that makes and returns an instance of the new class definition. All in all, the code looks like this:
}