gpt4 book ai didi

java - 在Spring服务方法中使用反射

转载 作者:太空宇宙 更新时间:2023-11-04 09:47:44 24 4
gpt4 key购买 nike

我已经在我的 Spring 应用程序中注册了一项服务。我有一些命名法几乎相同的方法。所以我使用反射来调用它们以避免使用 if else。下面是类似的场景。

@Service
public class MyService {
public List<String> getEmployee(String type) {
Class myServiceClass = Class.forName("MyService");
Class partypes[] = new Class[1];
partypes[0] = String.class;
Method meth = myServiceClass.getDeclaredMethod("getEmpBy"+type, partypes);
Object arglist[] = new Object[1];
arglist[0] = type;
meth.invoke(this, arglist);
}
}

现在我有命名为 getEmpByName、getEmpByAddress、getEmpByQualification 的方法。为了避免 if else 我想使用反射,但上面的代码无法在运行时加载 MyService

最佳答案

TLDR
这个设计太糟糕了。使用接口(interface)而不是反射。

更多信息
您正在使用 Spring。
Spring 很乐意将依赖项注入(inject)到您的 Controller 中。
几乎可以肯定,Spring 在注入(inject)依赖项时比执行反射时做得更好。
你的服务的调用接口(interface)是固定的(请注意,您对参数类型和参数顺序进行了硬编码)有趣的是,这与界面相同。

关于java - 在Spring服务方法中使用反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55211497/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com