Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your requirement to have <code>static</code> method doesn't leave much space for clean solution. One of the possible ways is to mix static and dynamic, and lose some CPU for a price of saving on RAM:</p> <pre><code>class Entity { private static final ConcurrentMap&lt;Class, EntityMetadata&gt; metadataMap = new ...; Entity(EntityMetadata entityMetadata) { metadataMap.putIfAbsent(getClass(), entityMetadata); } public static EntityMetadata getMetadata(Class clazz) { return metadataMap.get(clazz); } } </code></pre> <p>The way I would like more would be to waste a reference but have it dynamic:</p> <pre><code>class Entity { protected final EntityMetadata entityMetadata; public Entity(EntityMetadata entityMetadata) { this.entityMetadata=entityMetadata; } } class A extends Entity { static { MetadataFactory.setMetadataFor(A.class, ...); } public A() { super(MetadataFactory.getMetadataFor(A.class)); } } class MetadataFactory { public static EntityMetadata getMetadataFor(Class clazz) { return ...; } public static void setMetadataFor(Class clazz, EntityMetadata metadata) { ...; } } </code></pre> <p>You could get even get rid of <code>EntityMetadata</code> in <code>Entity</code> completely and leave it factory only. Yes, it would not force to provide it for each class in compile-time, but you can easily enforce that in the runtime. Compile-time errors are great but they aren't holy cows after all as you'd always get an error immediately if a class hasn't provided a relevant metadata part.</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