Miruuu
Miruuu

Reputation: 17

How to know the Dynamic type of a class?

My question is, how, or if its possible, to know the dynamic type of an object in the compilator. I have this data

public abstract class accommodation;
public class Hotel extends accomodation;
public class Cabin extends accomodation;
accomodation [] array=  new accomodation[x];

My actual problem is, can i get an array with only hotels from this?

Upvotes: 0

Views: 210

Answers (2)

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79875

Yes, there are a few ways to do this. One is to use the getClass() method. Because this is defined in the Object class, it can be called on every Java object.

System.out.println(myObject.getClass());

or even

if (myObject.getClass() == MyClass.class)

But if you only want to know whether an object is an instance of a particular class, you can write

if (myObject instanceof MyType)

which will return true if the class of myObject is MyType or any subtype thereof. You can use either an interface or a class for MyType here - even an abstract class.

However, as Tim pointed out in the comments, often there are better ways to design your program than relying on one of these ways of checking the class of an object. Careful use of polymorphism reduces the need for either of these.

Upvotes: 0

Sweeper
Sweeper

Reputation: 273805

One way is to use filter and map to first filter out all the objects that are Hotels, and cast to Hotel.

Arrays.stream(array)
    .filter(x -> x instanceof Hotel)
    .map(x -> (Hotel)x)
    .collect(Collectors.toList());

Upvotes: 2

Related Questions