I have a utility method and when irrelevant logic is removed from it, the simplified method would look like this:
public static <A extends Foo> List<A> getFooList(Class<A> clazz) { List<A> returnValue = new ArrayList<A>(); for(int i=0; i < 5; i++) { A object = clazz.newInstance(); returnValue.add(object); } return returnValue; }
The problem is, that if clazz is an inner class such as Foo.Bar.class, then the newInstance() method will not work even if Bar would be public, as it will throw a java.lang.InstantiationException.
Is there a way to dynamically instantiate inner classes?
If it’s genuinely an inner class instead of a nested (static) class, there’s an implicit constructor parameter, which is the reference to the instance of the outer class. You can’t use
Class.newInstanceat that stage – you have to get the appropriate constructor. Here’s an example: