Pattern, Abstract Factory / Factory
Rudi Araújo
rudi.araujo at gmail.com
Sat Feb 6 20:06:53 UTC 2021
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 at 6a4f787b
Created: REPL.$JShell$12$Bar at 7d9d1a19
Created: REPL.$JShell$13$Baz at 39c0f4a
On Sat, 6 Feb 2021 at 20:56, Luís Oliveira <luismbo at gmail.com> wrote:
> On Sat, 6 Feb 2021 at 16:29, Manfred Bergmann <manfred.bergmann at 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
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mailman.common-lisp.net/pipermail/pro/attachments/20210206/3d7d045d/attachment-0001.html>
More information about the pro
mailing list