Gondim
Gondim

Reputation: 3048

Cast with Expression Language

Is it possible to cast using EL?

I've got a class Vehicle, and two other classes Car and Bus that extends Vehicle. I'm searching for all Vehicles and there's some data that has in Bus but does not have in Car.

So I was trying to show things from Car when it's a Car and things from Bus when it's a Bus.

How could I do it, Cast, instanceof? And How would I do it, cause i'm kinda lost here.

Thanks

Upvotes: 10

Views: 9288

Answers (2)

Bozho
Bozho

Reputation: 597304

You can use ${obj.class.simpleName == 'Car'} but it's not the best thing thing to do.

Perhaps you can have a geType() abstract method and use it to differentiate. For example:

<c:forEach items="${vehicles}" var="vehicle">
   Reg.No: ${vehicle.registrationPlateNumber}
   <c:if test="${vehicle.type == 'bus'}">
      Toilets: ${vehicle.toilets}
   </c:if>
</c:forEach>

Upvotes: 9

Ali Raza
Ali Raza

Reputation: 1215

you will do it by extending car and bus from vehicle class(as vehicle will be parent class). For Example

public class Vehicle {
   public void speed(){
   // some code
  }
}
public class Car extends Vehicle {
    public void speed(){
    // some code
   }
}
public class Bus extends Vehicle {
   public void speed(){
    // some code
   }
}

now you can check while initiating them or getting that weather it is an instance of vehicle of not using instanceOf keyword.

i.e

if(new car() instanceOf Vehicle){
//somecode
}

Upvotes: -3

Related Questions