使用 java 8 lambda 表达式打印有关错误的调试信息 [英] Printing debug info on errors with java 8 lambda expressions

查看:36
本文介绍了使用 java 8 lambda 表达式打印有关错误的调试信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用静态方法作为 setter helper 来捕获异常并打印有关失败操作的调试信息.我不只想要异常详细信息.我想显示正在设置的属性,以便详细信息有助于快速调试问题.我正在使用 Java 8.

我应该如何提供或检测正在设置的属性?

我希望删除示例中的name"字符串并获得相同的结果.

我知道我不能对所提供的 setter 方法使用反射,该方法已转换为 lambda 表达式,然后转换为 BiConsumer.

我知道了,但需要提供属性名称.

/** setter 辅助方法 **/私有静态<E,V>void set(E o, BiConsumer<E, V> setter,供应商valueSupplier, String propertyName) {尝试 {setter.accept(o, valueSupplier.get());} catch (RuntimeException e) {throw new RuntimeException("无法设置" + propertyName, e);}}

示例:

 Person p = new Person();供应商<字符串>nameSupplier1 = () ->我的名字";供应商<字符串>nameSupplier2 = () ->{ 抛出新的 RuntimeException();};set(p, Person::setName, nameSupplier1, "name");System.out.println(p.getName());//打印我的名字set(p, Person::setName, nameSupplier2, "name");//抛出异常消息 Failed to set the value of nameSystem.out.println(p.getName());//不执行

我知道反射对 lambdas 没有帮助.我知道 AOP 并且我知道这也可以通过纯反射来实现,但是我想知道是否有更好的方法来使用 Java 8 完成此操作,而 Java 7 不存在.对我来说似乎应该这样做.现在可以做一些事情,比如将一个 setter 方法传递给另一个方法.

解决方案

如果您希望方法引用作为唯一的输入,您可以使用以下技巧将它们调试为可打印的名称:

public static void main(String[] args) {人 p = 新人();供应商<字符串>nameSupplier1 = () ->我的名字";供应商<字符串>nameSupplier2 = () ->{ 抛出新的 RuntimeException();};set(p, Person::setName, nameSupplier1);System.out.println(p.getName());//打印我的名字set(p, Person::setName, nameSupplier2);//用消息抛出异常System.out.println(p.getName());//不执行}接口 DebuggableBiConsumer扩展 BiConsumer, Serializable {}私有静态<E,V>空集(Eo,DebuggableBiConsumer<E,V>二传手,供应商<V>价值供应商) {尝试 {setter.accept(o, valueSupplier.get());} catch (RuntimeException e) {throw new RuntimeException("无法设置"+name(setter), e)的值;}}私有静态字符串名称(DebuggableBiConsumersetter){for (Class cl = setter.getClass(); cl != null; cl = cl.getSuperclass()) {尝试 {Method m = cl.getDeclaredMethod("writeReplace");m.setAccessible(true);对象替换 = m.invoke(setter);if(!(替换 SerializedLambda 的实例))break;//自定义接口实现SerializedLambda l = (SerializedLambda) 替换;返回 l.getImplClass() + "::" + l.getImplMethodName();}catch (NoSuchMethodException e) {}catch (IllegalAccessException | InvocationTargetException e) {休息;}}返回未知属性";}

限制是它不会为 lambda 表达式打印非常有用的方法引用(对包含 lambda 代码的合成方法的引用)和用于接口的自定义实现的 unknown property".>

I want to use a static method as setter helper that catch exceptions and print debug info about the operation that failed. I don't want the exception details only. I want to show what property was being set so that detail help to debug the problem quickly. I am working with Java 8.

How should I provide or detect the property being set?

What I wish is to remove the "name" string in the example and get the same result.

I know I can't use reflection over the supplied setter method supplied that is transformed to lambda expression and then to BiConsumer.

I got this but the property name needs to be provided.

/** setter helper method **/
private static <E, V> void set(E o, BiConsumer<E, V> setter,
        Supplier<V> valueSupplier, String propertyName) {
    try {
        setter.accept(o, valueSupplier.get());
    } catch (RuntimeException e) {
        throw new RuntimeException("Failed to set the value of " + propertyName, e);
    }
}

Example:

    Person p = new Person();
    Supplier<String> nameSupplier1 = () ->  "MyName";
    Supplier<String> nameSupplier2 = () -> { throw new RuntimeException(); };
    set(p, Person::setName, nameSupplier1, "name");
    System.out.println(p.getName()); // prints MyName
    set(p, Person::setName, nameSupplier2, "name"); // throws exception with message  Failed to set the value of name
    System.out.println(p.getName()); // Does not execute

EDIT: I know reflection does not help with the lambdas. I know AOP and I know this can be made with pure reflection too but I want to know if there a better way to get this done with Java 8 that didn't exist with Java 7. It seems it should to me. Now it is possible to do things like to pass a setter method to another one.

解决方案

In case you expect method references as the only input, you can debug them to printable names with the following trick:

public static void main(String[] args) {
  Person p = new Person();
  Supplier<String> nameSupplier1 = () -> "MyName";
  Supplier<String> nameSupplier2 = () -> { throw new RuntimeException(); };
  set(p, Person::setName, nameSupplier1);
  System.out.println(p.getName()); // prints MyName
  set(p, Person::setName, nameSupplier2); // throws exception with message
  System.out.println(p.getName()); // Does not execute
}

interface DebuggableBiConsumer<A, B> extends BiConsumer<A, B>, Serializable {}

private static <E, V> void set(
    E o, DebuggableBiConsumer<E, V> setter, Supplier<V> valueSupplier) {
  try {
    setter.accept(o, valueSupplier.get());
  } catch (RuntimeException e) {
    throw new RuntimeException("Failed to set the value of "+name(setter), e);
  }
}

private static String name(DebuggableBiConsumer<?, ?> setter) {
  for (Class<?> cl = setter.getClass(); cl != null; cl = cl.getSuperclass()) {
    try {
      Method m = cl.getDeclaredMethod("writeReplace");
      m.setAccessible(true);
      Object replacement = m.invoke(setter);
      if(!(replacement instanceof SerializedLambda))
        break;// custom interface implementation
      SerializedLambda l = (SerializedLambda) replacement;
      return l.getImplClass() + "::" + l.getImplMethodName();
    }
    catch (NoSuchMethodException e) {}
    catch (IllegalAccessException | InvocationTargetException e) {
      break;
    }
  }
  return "unknown property";
}

The limitations are that it will print not very useful method references for lambda expressions (references to the synthetic method containing the lambda code) and "unknown property" for custom implementations of the interface.

这篇关于使用 java 8 lambda 表达式打印有关错误的调试信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆