Aryeh said:
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.