Downcasting objects in Java actions

5
I'm writing a Java action in which I get given a list of objects of type Rule which contains a mixture of objects of different subtypes of Rule. How can I downcast them to their respective subtypes in Java code? I need the equivalent of the inheritance split / cast activity arrangement we use when doing this in microflows.
asked
2 answers
5

Assuming you're using Mendix proxy objects, you can just use the usual Java way of casting objects, since the proxies are automatically initialized as the most specific subclass:

import mynotsofirstmodule.proxies.SomeObject
...
if (randomObject instanceof SomeObject) {
    SomeObject someObject = (SomeObject) randomObject;
}
answered
4

The solution Alexander suggests could work, but for this to work you have to initialize the proxy object first. The problem with this is that the proxy checks if the object is of the correct type.

If you want to check these objects in java and use the solution from Alexander this could cause a problem. Because this only works if the 'randomObject' is actually a proxie object. And those can only be created if you know the type of the object.

It is probably safer to use the following Example:
For instance you have System.User. hrm.Employee inherits from user and hrm.SpecialEmployee inherits from hrm.Employee

if(  Core.isSubClassOf( hrm.proxies.SpecialEmployee.getType(), randomObject.getType() ) {
  //Do something
}else if(  Core.isSubClassOf( sytem.proxies.Employee.getType(), randomObject.getType() ) {
  //Do something
} else if(  Core.isSubClassOf( sytem.proxies.User.getType(), randomObject.getType() ) {
  //Do something
}
else {
  //This is a wrong object type
}

Usually when check for an object type is use this structure. This is the safest way even if somebody creates an object hrm.VerrySpecialEmployee every object of that type will go through the first if statement.

This way of programming works similar to the inheritance spilt in microflow.

answered