Note that there are some explanatory texts on larger screens.

plurals
  1. POAlternatives to static methods in Java
    text
    copied!<p>I'm making a mini ORM for a Java program I'm writing... there is a class for each table in my db, all inheriting from <code>ModelBase</code>.</p> <p><code>ModelBase</code> is abstract &amp; provides a bunch of static methods for finding &amp; binding objects from the db, for example:</p> <pre><code>public static ArrayList findAll(Class cast_to_class) { //build the sql query &amp; execute it } </code></pre> <p>So you can do things like <code>ModelBase.findAll(Albums.class)</code> to get a list of all persisted albums. My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like </p> <pre><code>public class Album extends ModelBase { public static String getSelectSQL() { return "select * from albums.....";} } </code></pre> <p>because there is no polymorphism for static methods in Java. But I don't want to make <code>getSelectSQL()</code> an instance method in <code>Album</code> because then I need to create an instance of it just to get a string that is really static in behavior.</p> <p>At the moment, <code>findAll()</code> uses reflection to get the appropriate sql for the class in question:</p> <pre><code>select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null); </code></pre> <p>But that's pretty gross. </p> <p>So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know <em>why</em> static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!</p> <p>Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?</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