I am writting a generic instance creator and for various reasons want
to always use the default ctor (the one that
obj.getClass().newInstance() uses) but just got to thinking what
happens if the there is no public default ctor (or no default at all)
Lew - 13 Oct 2007 19:23 GMT
> I am writting a generic instance creator and for various reasons want
> to always use the default ctor (the one that
> obj.getClass().newInstance() uses) but just got to thinking what
> happens if the there is no public default ctor (or no default at all)
This question is readily resolvable from the reference materials at hand.
Let's not use the term "default" constructor, which has a specific meaning in
the JLS. Let's talk of the "no-arg" constructor,
Foo()
If the class lacks that constructor, the call to newInstance() will fail. If
the class has that constructor but the caller cannot access it, say, if it
were private, the call will fail.
Have you read
<http://java.sun.com/javase/6/docs/api/java/lang/Class.html#newInstance()>
? That would be the place that reveals all this information, and presumably
the first place you'd go to find it.
Under what circumstances would there not exist a no-arg constructor?
This is a basic Java language question.
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8>
and
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.8.9>
cover this, but the summary is that a no-arg constructor exists unless you
declare a constructor overload that takes arguments but do not define a no-arg
constructor.
Accessibility is controlled by the presence or absence of access keywords in
the no-arg constructor definition, or by the rules in [JLS ss. 8.8.9] if it's
the implicit constructor.
Iff the class has an accessible, no-arg constructor whose initialization does
not fail and whose invocation raises no exception, then the newInstance() will
succeed.

Signature
Lew
Roedy Green - 13 Oct 2007 21:43 GMT
On Sat, 13 Oct 2007 16:53:22 -0000, "Aryeh M. Friedman"
<Aryeh.Friedman@gmail.com> wrote, quoted or indirectly quoted someone
who said :
>happens if the there is no public default ctor (or no default at all)
If there is no constructor at all, Java kindly provides one. However,
if you create a only a private constructor, there won't be a public
constructor. You can only create the objects via a factory that has
private access.

Signature
Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com
Arne Vajhøj - 15 Oct 2007 02:27 GMT
> I am writting a generic instance creator and for various reasons want
> to always use the default ctor (the one that
> obj.getClass().newInstance() uses) but just got to thinking what
> happens if the there is no public default ctor (or no default at all)
It would only take 2 minutes to write code that revealed
which exception you will get.
Arne