Cast with Expression Language
Asked Answered
N

2

10

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

Neoplasty answered 18/10, 2011 at 13:7 Comment(1)
I want to do it to show some data of Bus for example in EL, not on JavaNeoplasty
K
9

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>
Kraken answered 18/10, 2011 at 13:11 Comment(4)
How could I display if a Bus has a toilette if only Bus has it's method, I mean, how would I display the value of this attribute.Neoplasty
getType() would be the same as instenceof and the same as .simpleName. You make an if to check.Kraken
As I still a bit lost, would you mind giving me an example of how to reach some attribute from Bus?Neoplasty
Thank you very much!! I was doing that but had not tried to run, cause it was saying "Unknown property..." but it worked properly!Neoplasty
T
-3

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
}
Tengler answered 18/10, 2011 at 13:17 Comment(1)
I want to access it from a JSF page, using Expression LanguageNeoplasty

© 2022 - 2024 — McMap. All rights reserved.