2

Let's say I have the following classes:

class Apple extends Fruit { ... }
class Banana extends Fruit { ... }
class Grape extends Fruit { ... }
class Kiwi extends Fruit { ... }

And so on and so forth. I now need to display a dropdown that contains a list of all the discriminator values of all subclasses that extend Fruit, so for example:

<select name="fruitType">
    <option value="Apple">Apple</option>
    <option value="Apple">Banana</option>
    <option value="Apple">Grape</option>
    <option value="Apple">Kiwi</option>
</select>

This is easy enough to hard-code for 4 of these, but in my actual domain there's the potential for this list to get quite long. Is there any way of getting a list of all the discriminator values for all subclasses that implement a base type? Something like this, for example:

Fruit.class.getAllDiscriminatorValues()
Daniel T.
  • 37,212
  • 36
  • 139
  • 206
  • P.S. The workaround we've been using so far is to create a static enum with all the types, e.g. `public static enum FruitType {Apple, Banana, Grape, Kiwi}`, but this isn't really a maintainable solution. – Daniel T. Dec 06 '12 at 03:14

1 Answers1

2

You could do this:

def getAllFruitSubclasses() {

   def fruit = []

   grailsApplication.domainClasses.each { 
      if (it.clazz.superclass == 'com.whatever.Fruit') {
         fruit << it.clazz.simpleName
      }
   }
   return fruit
}
Gregg
  • 34,973
  • 19
  • 109
  • 214