Instead of passing a Class to create an instance with, which means having to deal with catching or throwing exceptions, you could pass a Supplier<T> instead.
java.util.function.Supplier<T>, (a Java 8 feature), is a functional interface that has one method get, which returns an object of the type T.
Using a Supplier<T> would look like this:
public static <T extends HotelBean> List<T> fill(Supplier<T> supp) { // No more exceptions!
List<T> list = new ArrayList<>();
for (int i = 0; i <= 2; i++) {
T t = supp.get();
list.add(t);
}
return list;
}
You can pass method references that take no arguments and return an object of type T, as a supplier, which includes a default constructor of T.
class MyClass {
public MyClass() {...}
}
fill(MyClass::new);
The main difference with newInstance(), is that the object returned from a Supplier<T> is not necessarily a new object, because you don't have to necessarily pass MyClass::new. You could pass any method that takes no arguments and returns a T.
T. The only way to get rid of the parameter would be to have the type ofTbe defined in some reflection data, i.e. a field definition or class with a concrete type. That, however, would probably contradict the purpose of your method or at least not be easier than passing a parameter.Class.Supplier<T>instead, using aMyType::newmethod reference as an argument. That would at least get rid of the throws clauseSupplier<T>? I am very interested of your solution.