Also, a slightly Lispier way to do what you want: List.of(Foo.class, Bar.class, Baz.class).stream().map(c -> { try { return c.newInstance(); } catch(Exception e) { e.printStackTrace(); return null; } }).collect(Collectors.toList());
The Stream API and lambdas make it almost pleasant to work with Java, but exception handling is still a bit tricky... On Sat, 6 Feb 2021 at 21:06, Rudi Araújo <rudi.ara...@gmail.com> wrote: > Class::newInstance() doesn't have any parameters (also, it's deprecated: > better to use getConstructor() or getDeclaredConstructor() and call > newInstance() on it). > > Also, the generic agreement on your calls to makeAndPrint is failing. > > This does what you wanted: > > jshell> class Foo { } > | modified class Foo > > jshell> class Bar extends Foo { } > | modified class Bar > > jshell> class Baz extends Foo { } > | modified class Baz > > jshell> class Main { > ...> public static void main(String[] args) { > ...> makeAndPrint(Foo.class); > ...> makeAndPrint(Bar.class); > ...> makeAndPrint(Baz.class); > ...> } > ...> > ...> public static void makeAndPrint(Class<? extends Foo> klass) { > ...> try { > ...> Object o = klass.newInstance(); > ...> System.out.println("Created: " + o.toString()); > ...> } catch (Exception e) { > ...> System.err.println("Failed: " + klass); > ...> } > ...> } > ...> } > | created class Main > > jshell> Main.main(new String[]{}) > Created: REPL.$JShell$11$Foo@6a4f787b > Created: REPL.$JShell$12$Bar@7d9d1a19 > Created: REPL.$JShell$13$Baz@39c0f4a > > > On Sat, 6 Feb 2021 at 20:56, Luís Oliveira <luis...@gmail.com> wrote: > >> On Sat, 6 Feb 2021 at 16:29, Manfred Bergmann <manfred.bergm...@me.com> >> wrote: >> > But this is kind of also possible in i.e. Java where you can say: >> > Foo.class.newInstance() which uses reflection and is not normally used. >> > But is effectively similar to make-instance `foo. >> >> My Java is getting rustier and rustier, but maybe you can tell me why >> the following program doesn't compile: >> >> class Foo { } >> class Bar extends Foo { } >> class Baz extends Foo { } >> >> class Main { >> public static void main(String[] args) { >> makeAndPrint(Foo.class); >> makeAndPrint(Bar.class); >> makeAndPrint(Baz.class); >> } >> >> public static void makeAndPrint(Class<Foo> klass) { >> try { >> Object o = klass.newInstance(klass); >> System.out.println("Created: " + o.toString()); >> } catch (Exception e) { >> System.err.println("Failed: " + klass); >> } >> } >> } >> >> The rough equivalent in Common Lisp would be: >> >> (defclass foo () ()) >> (defclass bar (foo) ()) >> (defclass baz (foo) ()) >> >> (mapcar #'make-instance '(foo bar baz)) >> >> Luís >> >> > > -- > He who binds to himself a joy > Doth the winged life destroy > But he who kisses the joy as it flies > Lives in Eternitys sun rise > > - William Blake > -- He who binds to himself a joy Doth the winged life destroy But he who kisses the joy as it flies Lives in Eternitys sun rise - William Blake