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 luismbo@gmail.com wrote:
On Sat, 6 Feb 2021 at 16:29, Manfred Bergmann manfred.bergmann@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