Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails/Groovy domain classes inheritance cast

I have modeled my domain classes in Grails with inheritance as shown below.

abstract class Profile{
}

class Team extends Profile{
}

class User extends Profile{
}

class B{
    static hasMany = [profiles: Profile]
}

Later in the controllers when I get all profiles from the class B in some situations I'd like to cast some of the profiles to Team or to User, but I can't because I get a java.lang.ClassCastException or GroovyCastException, although they are saved as a Team or User (with the attribute class in the database). Here are the ways I have tried:

def team1 = b.profiles.toList()[0] as Team

def team1 = (Team)b.profiles.toList()[0]

It is working when I don't write any type just use it as it is normal in a dynamic language.

def team1 = b.profiles.toList()[0]

But then I never know which class I am using. Is there anyway in groovy or gorm to cast the parent class to child?

like image 857
sgleser87 Avatar asked Jul 11 '12 09:07

sgleser87


People also ask

What is grails domain class?

In Grails a domain is a class that lives in the grails-app/domain directory. A domain class can be created with the create-domain-class command: grails create-domain-class org.bookstore.Book. or with your favourite IDE or text editor.

What is grails Gorm?

GORM is the data access toolkit used by Grails and provides a rich set of APIs for accessing relational and non-relational data including implementations for Hibernate (SQL), MongoDB, Neo4j, Cassandra, an in-memory ConcurrentHashMap for testing and an automatic GraphQL schema generator.

How do I create a domain class in grails?

If you don't specify a package (like "org. bookstore" in the example), then the name of the application will be used as the package. So if the application name is "bookstore" and you run create-domain-class Book , then the command will create the file grails-app/domain/bookstore/Book.

What is Groovy on grails?

Groovy-Based Apache Groovy is a language for the Java platform designed to enhance developers' productivity. It is an optionally-typed and dynamic language but with static-typing and static compilation capabilities.


1 Answers

The answer is No as a real GORM/Hibernate instance is a proxied object. So it cannot be cast to an entity class directly.

Anyway this might help:

def team1 = b.profiles.toList()[0]
if(team1.instanceOf(Team)) {
    // I am an instance of Team
    // do something here.
}
like image 95
chanwit Avatar answered Sep 21 '22 19:09

chanwit