Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>If you want to base the behavior on an interface, you could use a static initializer in that interface.</p> <pre><code>public interface Foo{ static{ // do initializing here } } </code></pre> <p>I'm not saying it's good practice, but it will definitely initialize the first time one of the implementing classes is loaded.</p> <p><strong>Update:</strong> static blocks in interfaces are illegal. Use abstract classes instead!</p> <p><strong>Reference:</strong></p> <ul> <li><a href="http://download.oracle.com/javase/tutorial/java/javaOO/initial.html" rel="nofollow noreferrer" title="Page title: initializing fields. But it doesn&#39;t only apply to fields.">Initializers</a> (Sun Java Tutorial)</li> </ul> <hr> <p>But if I understand you right, you want the initialization to happen once per implementing class. That will be tricky. You definitely can't do that with an interface based solution. You could do it with an abstract base class that has a dynamic initializer (or constructor), that checks whether the requested mapping already exists and adds it if it doesn't, but doing such things in constructors is quite a hack.</p> <p>I'd say you cleanest options are either to generate Code at build time (through annotation processing with apt or through bytecode analysis with a tool like asm) or to use an agent at class load time to dynamically create the mapping.</p> <hr> <p>Ah, more input. Very good. So clients use your library and provide mappings based on annotations. Then I'd say your library should provide an initializer method, where client code can register classes. Something like this:</p> <pre><code>YourLibrary.getInstance().registerMappedClasses( CustomClass1.class, CustomClass2.class, CustomClass3.class, CustomClass4.class ) </code></pre> <p>Or, even better, a package scanning mechanism (example code to implement this can be found <a href="https://stackoverflow.com/questions/1456930/read-all-classes-from-java-package-in-classpath">at this question</a>):</p> <pre><code>YourLibrary.getInstance().registerMappedClassesFromPackages( "com.mycompany.myclientcode.abc", "com.mycompany.myclientcode.def" ) </code></pre> <p>Anyway, there is basically no way to avoid having your clients do that kind of work, because you can't control their build process nor their classloader for them (but you could of course provide guides for classloader or build configuration).</p>
 

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