【问题标题】:Retrieve static argument values used within statically declared functional interfaces via java reflection通过 java 反射检索在静态声明的功能接口中使用的静态参数值
【发布时间】:2017-09-21 15:24:28
【问题描述】:

在这里看看我的代码:

import java.util.function.Function;

public class StaticArgumentsTest {

    static Function<String, String> staticConsumer(String testValue) {
        return (st) -> testValue + " and " + st;
    }

    static final Function<String, String> aStaticConsumer =
            staticConsumer("Static String Example Value");

    public static void main(String[] args) {
        System.out.println(StaticArgumentsTest.aStaticConsumer.apply("Dynamic String Example Value"));
    }
}

我们有一些带有许多此类功能接口实现的遗留代码,我宁愿让这些代码像数据库一样处于更易于管理的状态,而不是在纯 java 代码中使用这些设置。所以我的问题是,是否可以使用反射找到上面看到的字符串值“静态字符串示例值”?我可能宁愿这样做,而不仅仅是为这些东西编写我自己的 java 代码解析器,但据我所知,我坚持这样做。

【问题讨论】:

  • 就像你对普通对象所做的那样......
  • 我确实想到了这一点,并尝试了许多不同的方法使用反射来产生这些字符串值,但我一直没能做到。我应该在我的问题中发布其中一些示例以供参考吗?我以为我已经明确表示我无法产生结果,而不是我只是没有尝试过。如果我的问题令人困惑,我深表歉意。
  • 当然,如果您尝试过,请发布它们。 Stackoverflow 用户通常希望看到一些努力,此外,可能只是缺少一点点东西才能使示例正常工作。没有看到他们,我们无法分辨。

标签: java reflection static static-methods functional-interface


【解决方案1】:

当然,这是高度依赖实现的,不推荐用于生产代码,但对于一次性转换任务,它将与普通反射操作和 HotSpot/OpenJDK 的当前实现一起使用:

public class StaticArgumentsTest {

    static Function<String, String> staticConsumer(String testValue) {
        return (st) -> testValue + " and " + st;
    }

    static final Function<String, String> aStaticConsumer =
            staticConsumer("Static String Example Value");

    public static void main(String[] args) {
        System.out.println(aStaticConsumer.apply("Dynamic String Example Value"));
        getCapturedValues(aStaticConsumer);
    }

    private static void getCapturedValues(Object instance) {
        Field[] f = instance.getClass().getDeclaredFields();
        AccessibleObject.setAccessible(f, true);
        for(Field field: f) {
            System.out.print(field.getName()+" ("+field.getType()+"): ");
            try { System.out.println(field.get(instance)); }
            catch(ReflectiveOperationException ex) { System.out.println(ex); }
        }
    }
}
Static String Example Value and Dynamic String Example Value
arg$1 (class java.lang.String): Static String Example Value

当然,这些合成字段没有有意义的名称,但是对于仅捕获一个值的 lambda 表达式,这是显而易见的,而对于其他字段,您可以使用一些合理的启发式方法,例如根据类型或顺序,找出哪个字段对应哪个变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2011-03-26
    • 2018-07-10
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    相关资源
    最近更新 更多