简体   繁体   English

反射或运行时类声明?

[英]reflection or runtime class declaring?

well I have a simple question. 好吧,我有一个简单的问题。

we are working on a simple application server(like), and this server accepts clients business at runtime without restarting the server. 我们正在使用简单的应用程序服务器(例如),并且该服务器在运行时接受客户端业务,而无需重新启动服务器。

When user implements it's business and deploy it to the server, server just try to find out the archive descriptor, and load the modules, and it works good. 当用户实现它的业务并将其部署到服务器时,服务器只需尝试找出存档描述符,然后加载模块,即可正常工作。

some operations need to much reflection calls, and for each call they called again and again. 一些操作需要大量的反射调用,并且对于每个调用,它们都会反复调用。 for example there is a method which accepts any object, then search for a certain field witch has signed by a annotation and do some business with it, so if we call this method 1000 times with one same object, this is going to reflect 1000 times. 例如,有一种方法可以接受任何对象,然后搜索某个已通过注释签名的特定字段并对其进行处理,因此,如果我们对一个相同的对象调用此方法1000次,这将反映1000次。

my question is, is it efficient? 我的问题是,效率高吗? I mean doesn't it eat up the CPU?! 我的意思是它不占用CPU吗?! the only possible solution I'm thinking is that create a class and compile it for each object(maybe wrapper) and the method will just find out the wrapper class. 我在想的唯一可能的解决方案是创建一个类并为每个对象(可能是包装器)进行编译,然后该方法将找出包装器类。 but I know this may make the system complex, and hard to debug. 但是我知道这可能会使系统变得复杂,并且难以调试。

current solution is working, but I think doing a work 1000 times is kinda not logical even it's simple and easy. 当前的解决方案是可行的,但是我认为完成1000次工作是不合逻辑的,即使它很简单也很容易。

Thanks in advanced. 提前致谢。

The use of reflection to dynamically load classes at runtime is not a bad choice per-se. 本质上,使用反射在运行时动态加载类并不是一个坏选择。 Based on your description, you should provide an extensible framework that allows your client to make an implementation, and run their business logic based on that instead of some implicit run-time annotated magic. 根据您的描述,您应该提供一个可扩展的框架,该框架允许您的客户进行实施,并基于该框架运行其业务逻辑,而不是一些隐含的运行时注释魔术。

A good real-world example for this off the top of my head is The Servlet API . Servlet API就是一个很好的现实世界例子。

for example there is a method which accepts any object, then search for a certain field witch has signed by a annotation and do some business with it, so if we call this method 1000 times with one same object, this is going to reflect 1000 times. 例如,有一种方法可以接受任何对象,然后搜索某个已通过注释签名的特定字段并对其进行处理,因此,如果我们对一个相同的对象调用此方法1000次,这将反映1000次。

In this case I suggest you to use caching. 在这种情况下,建议您使用缓存。 After reflection is finished you'll know class name and the field name. 反射完成后,您将知道类名称和字段名称。 Store them in a HashMap with Class type key and a Method as a value. 将它们存储在具有Class类型键和Method作为值的HashMap Next time you invoke "the method" check cache first. 下次调用“方法”时,将首先检查缓存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM