This example defines the Person class:
package com.me;
public class Person {
private String name;
private Integer age;
public Person() {
this.name = "Max Mule";
this.age = 10;
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
This example defines the Employee class that extends the Person class:
package com.me;
public class Employee extends Person {
private String company;
public Employee(String name, Integer age, String company) {
super(name, age);
this.company = company;
}
}
|
|
The classes used with the Java module must be exported (unless they belong to the default package). If not, the
execution fails with a JAVA:CLASS_NOT_FOUND error. See how to
export resources.
|
To check whether an object belongs to a certain class, an instance of the object is needed.
This can be done by calling the new operation to create an
Employee object and place it in the jane variable:
<java:new class="com.me.Employee"
constructor="Employee(String, Integer, String)"
target="jane">
<java:args>#[{
name: 'Jane Avi',
age: 28,
company: MuleSoft
}]</java:args>
</java:new>
To check if the object stored in vars.jane belongs to the Employee class, the Validate type
operation can be used:
<java:validate-type class="com.me.Employee" instance="#[vars.jane]" />
In this case, the object is an instance of Employee, so the flow continues
executing normally, and the payload is not modified.
Check Against Subtypes (Inheritance)
The Validate type operation has the Accept subtypes parameter,
which indicates if the operation should accept all subclasses of a class.
This parameter can be true, false, or an expression, and it defaults to true if omitted.
Continuing with the previous example, the object in vars.jane belongs to the
Employee class which extends the Person class, that is, Employee is a subtype
of Person. So executing this example resolves to true and the
flow executes normally.
<java:validate-type
class="com.me.Person"
instance="#[vars.jane]"
acceptSubtypes="true" />
|
|
Omitting the Accept subtypes parameter defaults its value to true.
|
The previous code is equivalent to:
<java:validate-type
class="com.me.Person"
instance="#[vars.jane]" />
However, when setting the Accept subtypes to false:
<java:validate-type
class="com.me.Person"
instance="#[vars.jane]"
acceptSubtypes="false" />
During execution the operation throws an error, interrupting the flow and passing
control to the error handler.