Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>That's because it's required to create a new instance via reflection.</p> <p><a href="http://www.docjar.com/html/api/java/util/ServiceLoader.java.html" rel="nofollow">I guess here's relevant code, line 362</a>:</p> <pre><code>S p = service.cast(Class.forName(cn, true, loader).newInstance()); </code></pre> <p>Thus it invokes "parameterless" constructor since <a href="http://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html" rel="nofollow"><code>Class.newInstance()</code> can only invoke the zero-argument constructor</a>.</p> <p><strong>Edit:</strong></p> <p>Actually, it's not <em>required</em> to create a zero-argument constructor for <code>public class</code> unless you define another constructor.</p> <p><a href="http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html" rel="nofollow">javadoc</a>: </p> <blockquote> <blockquote> <p>You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.</p> </blockquote> </blockquote> <p>So, the following code is perfectly correct:</p> <pre><code>public final class MyServiceImpl implements MyService { @Override public long getTime() { return System.currentTimeMillis(); } } </code></pre> <p>Default constructor for <code>MyServiceImpl</code> will be the same as:</p> <pre><code>public MyServiceImpl() { } </code></pre> <p>Since <code>MyServiceImpl</code> <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.8.9" rel="nofollow">is a public class</a>:</p> <blockquote> <blockquote> <p>if the class is declared public, then the default constructor is implicitly given the access modifier public</p> </blockquote> </blockquote> <p>Thus constructor in <code>MyServiceImpl</code> is redundant. </p> <p>My guess is that author of the blog post just wanted to make sure that <code>ServiceLoader</code> will be able to instantiate <em>service provider</em> even when it contains some explicit constructors with arguments.</p> <hr> <p><strong>Conclusion:</strong> <em>Service provider</em> <strong>should</strong> have explicit no-argument constructor only if it contains explicit constructors with arguments. Default constructor will suffice otherwise.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload