0

I need to write a extension module with static methods for a specific class and theese methods will be called by his childrens. By example, i have the following definitions:

Classes

abstract class Animal {
}

class Bird extends Animal {
}

class Dog extends Animal {
}

Extension Module

class AnimalStaticExtensions {

    static doSomethingBasedOnType(Animal selfType) {
        if(selfType instanceof Bird) {
            println("Fly")
        } else if(selfType instanceof Dog) {
            println("Bark")
        }
    }
}

Main code

Bird.doSomethingBasedOnType() // I need to get the Bird class here
Dog.doSomethingBasedOnType() // I need to get the Dog class here

When run the main code, the method doSomethingBasedOnType is called but don't work because the argument selfType for a static extension methods is unused and his value is always null.

There is some way to get the class type from a static extension module?

Community
  • 1
  • 1
Lucas Weyne
  • 1,107
  • 7
  • 17
  • have you also tried making doSomethingBasedOnType a static declaration in each child ? – V H Jun 08 '17 at 17:35
  • I need the method to be generic. Make sense create a static declaration in each child if the method only performs a lot of `if` and `else` to check the class type, but in my real case i have a lot of classes and one extension method to resolve everything that i need. To perform it, i need to retrieve the class type – Lucas Weyne Jun 08 '17 at 18:22
  • https://stackoverflow.com/questions/35864998/add-extension-module-to-groovy-class – Rao Jun 08 '17 at 18:50
  • @LucasWeyne ye from static to non static will cause problems, Unsure if the AnimalStaticExtension really needs to be a static as in it probably does from where you are - but in theory you could have grails services that does that bit and then calls in relevant object. take a look at https://github.com/vahidhedayati/grails-queuekit-plugin I have classes extending but then the logic to work out instanceOf class etc which really if you think about it no need to check instances of each instance has underlying call method to run (from service it can directly call methods) without static complicatio – V H Jun 08 '17 at 18:54
  • @vahid I try to create is a set of methods to perform persistence like GORM methods to a group of Java classes from a legacy .jar lib. Something like `LibObject.count()`, `LibObject.get(2)`. Some methods needs to be static and generic. I have a grails service to do this, but I want to put on static extension method to call like grails call your methods for domain classes. I already solve this with `ExpandoMetaClass`, but I need to create a library to group all set of methods (static and non static) to do the persistence job like grails do. – Lucas Weyne Jun 08 '17 at 20:53
  • With `ExpandoMetaClass` I can do this only using the `delegate` closure keyword, but on static extension modules is not possible – Lucas Weyne Jun 09 '17 at 11:46

0 Answers0