模板对象的Java 8功能构造函数 [英] Java 8 functional constructor from templated object
问题描述
我正在使用Eclipse Luna服务版本2(4.4.2),Java 8 u51。
我试图创建一个方法来创建一个基于另一个方法参数传递对象。原型被简化为
public< T> T test(Object param,T instance){
构造函数<?>构造函数= instance.getClass()。getConstructors()[0]; //我实际上选择了一个合适的构造函数
// eclipse reports未处理的异常类型InvocationTargetException
函数< Object,Object> createFun = constructor :: newInstance;
T result =(T)createFun.apply(param);
返回结果;
符合函数
声明eclipse报告未处理的异常类型InvocationTargetException
编译器错误。我需要 Function
以稍后在流中使用。
我尝试添加各种try / catch块,抛出声明,但没有修复此编译器错误。如何使这段代码工作?
你不能从一个函数
目标类型,因为它的 apply
方法不会引发异常。所以你需要把它变成一个未经检查的异常,例如通过包装它:
函数< Object,Object> createFun = o - > {
尝试{
return constructor.newInstance(o);
catch(InstantiationException | InvocationTargetException | IllegalAccessException e){
抛出new RuntimeException(e);
}
};
另一种方法是引导编译器认为它是一个未经检查的异常,它产生一个更干净的堆栈跟踪vs 。上面的选项:
函数< Object,Object> createFun = o - > {
尝试{
return constructor.newInstance(o);
} catch(InstantiationException | InvocationTargetException | IllegalAccessException e){
return uncheck(e);
}
};
使用以下实用程序方法:
@SuppressWarnings(unchecked)
public static< E extends Throwable,T> T uncheck(Throwable t)抛出E {
throw((E)t);
}
I am using Eclipse Luna Service Release 2 (4.4.2), Java 8 u51.
I'm trying to create a method which will create instances of a passed 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;
}
On line with Function
declaration eclipse reports Unhandled exception type InvocationTargetException
compiler error. I need the Function
to later use in a stream.
I tried to add various try/catch blocks, throws declarations, but nothing fixes this compiler error.
How to make this code work?
You can't throw a checked exception from a lambda with a Function
target type because its apply
method does not throw an exception. So you need to make it into 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);
}
};
An alternative is to lead the compiler to think it's an unchecked exception, which produces a cleaner stack trace vs. the option above:
Function<Object, Object> createFun = o -> {
try {
return constructor.newInstance(o);
} catch (InstantiationException | InvocationTargetException | IllegalAccessException e) {
return uncheck(e);
}
};
With the following utility method:
@SuppressWarnings("unchecked")
public static <E extends Throwable, T> T uncheck(Throwable t) throws E {
throw ((E) t);
}
这篇关于模板对象的Java 8功能构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!