【问题标题】:Dynamic String creation from property value从属性值创建动态字符串
【发布时间】:2021-07-28 09:47:53
【问题描述】:

我有我的 application.properties:

test.md5.params=something1,something4

在我的 java 类中,我得到了这个特定的值: 并且需要创建与属性文件中相同的字符串,例如

 public String calculate(RequestClass request)
       {
       List<String> params= //I am getting the values from application.prop  
        **(above part id done)**
       

我的问题如下:: 现在在我的参数列表中我有[something1,something4] 所以我需要连接两个字符串值,如下所示:

       String finalString=request.getSomething1()+request.getSomething4();
       return finalString;
       }

我的问题是如何动态地执行此操作,并且在我的属性文件中,我可能会收到“n”个值。 注意:我需要使代码保持我的类保持不变,如果将来我在属性文件中添加 10 个以上的值,我的最终字符串应该返回像

   String finalString=request.getSomething1()+request.getSomething4()+....all the values.;

【问题讨论】:

  • @Value注解与SPEL stackoverflow.com/a/12580260/9050514一起使用
  • 已经完成了@deadshot,请再次阅读我的问题。
  • 从 params 你怎么得到request.getSomethingN(),我看不出这两件事之间有任何关联。
  • 什么是RequestClass?你不能有一个getValue(String) 方法吗?如果您更改属性中的配置,您是否还需要更新该类? (旁注:我认为 Spring 部分在这里无关紧要,您应该将其从问题中删除,因为它使人们感到困惑,如 cmets 和重复提案中所见)

标签: java spring java-8


【解决方案1】:

通过反射这是可能的,下面是一种实现。

public String calculate(RequestClass request) throws InvocationTargetException, IllegalAccessException {
    List<String> params = Arrays.asList("something1", "something4");

    // Do your logic to get the method Names from params, below is an simple example - paramsUpdated
    List<String> paramsUpdated = Arrays.asList("getSomething1", "getSomething4");

    // Reflection to get the methods of request class
    Method[] methods = request.getClass().getMethods();
    StringBuilder sb = new StringBuilder();

    for (String param : paramsUpdated) {
        for (Method method : methods) {
            if (param.equals(method.getName())) { 
                sb.append(method.invoke(request));
            }
        }

    }

    return sb.toString();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多