eclipse - Java 8 functional constructor from templated object -


i using eclipse luna service release 2 (4.4.2), java 8 u51.

i'm trying create method create instances of passed object based on method parameter. prototype simplified

public <t> t test(object param, t instance) {     constructor<?> constructor = instance.getclass().getconstructors()[0]; // choose proper constructor      // eclipse reports "unhandled exception type invocationtargetexception"     function<object, object> createfun = constructor::newinstance;      t result = (t) createfun.apply(param);     return result; } 

on line function declaration eclipse reports unhandled exception type invocationtargetexception compiler error. need function later use in stream.

i tried add various try/catch blocks, throws declarations, nothing fixes compiler error.

how make code work?

you can't throw checked exception lambda function target type because apply method not throw exception. need make unchecked exception, example wrapping it:

function<object, object> createfun = o -> {   try {     return constructor.newinstance(o);   } catch (instantiationexception | invocationtargetexception | illegalaccessexception e) {     throw new runtimeexception(e);   } }; 

an alternative lead compiler think it's unchecked exception, produces cleaner stack trace vs. option above:

function<object, object> createfun = o -> {   try {     return constructor.newinstance(o);   } catch (instantiationexception | invocationtargetexception | illegalaccessexception e) {     return uncheck(e);   } }; 

with following utility method:

@suppresswarnings("unchecked") public static <e extends throwable, t> t uncheck(throwable t) throws e {   throw ((e) t); } 

Comments