Java 8 function constructor from templated object

I am using eclipse Luna service release 2 (4.4.2), Java 8 U51

I'm trying to create a method that will create an instance of the passing object based on another method parameter The prototype is simplified to

public <T> T test(Object param,T instance) {
    Constructor<?> constructor = instance.getClass().getConstructors()[0]; // I actually choose a proper constructor

    // eclipse reports "Unhandled exception type InvocationTargetException"
    Function<Object,Object> createFun = constructor::newInstance;

    T result = (T) createFun.apply(param);
    return result;
}

Eclipse reports unhandled exception type invocationtargetexception compiler error consistent with function declaration I need the function to be used in the stream later

I tried to add various try / catch blocks and throw declarations, but I didn't fix this compiler error

How do I make this code work?

Solution

You cannot throw a checked exception from a lambda with a function target type because its apply method does not throw an exception Therefore, you need to set it as an unchecked exception, for example, by wrapping it:

Function<Object,Object> createFun = o -> {
  try {
    return constructor.newInstance(o);
  } catch (InstantiationException | InvocationTargetException | illegalaccessexception e) {
    throw new RuntimeException(e);
  }
};

Another way is to guide the compiler to consider it an unchecked exception and produce a clearer stack trace with the above options:

Function<Object,Object> createFun = o -> {
  try {
    return constructor.newInstance(o);
  } catch (InstantiationException | InvocationTargetException | illegalaccessexception e) {
    return uncheck(e);
  }
};

Use the following practical methods:

@SuppressWarnings("unchecked")
public static <E extends Throwable,T> T uncheck(Throwable t) throws E {
  throw ((E) t);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>