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?
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.
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.
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.
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With