开发者

Adding a Convienience Method to Existing Class (Class Cast Exception)

Java/Android noob here (Still) I hoped you could help.

I was trying to add a small convenience method to get the number of time that has passed rather than the number of time since EPOCH.

So I tried to do this:

public class EasyLocation extends android.location.Location {

    ...

    public long getElapsedTime() {
        return getTime() - System.currentTimeMillis();
    }
}

However when I tried to use it like in the code below which casts it to my Location class. I got a class cast exception. I've read up on it and I fully understand why it doesn't work. That's not the issue.

The issue is: it's not a train smash but I would like to have what is returned to have my method on it to make the rest of my code a bit cleaner. I can't figure out a way around it. Any ideas on how to do that?

lastNetworkLocation = (Easy开发者_JAVA技巧Location) locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

Thanks,

Gerard.


You can't do it like that. (A Location is not an EasyLocation.)

I believe what you're looking for is the decorator pattern.

You would typically do something like this:

public class EasyLocation extends android.location.Location {

    public EasyLocation(Location loc) {
        // copy data from loc to this.
        super(loc);
    }
    ...

    public long getElapsedTime() {
        return getTime() - System.currentTimeMillis();
    }
}

And instead of doing

lastNetworkLocation =
    (EasyLocation) locationManager.getLastKnownLocation(
                                              LocationManager.NETWORK_PROVIDER);

you do

lastNetworkLocation =
    new EasyLocation(locationManager.getLastKnownLocation(
                                              LocationManager.NETWORK_PROVIDER));

Keep in mind though that most people would probably say "Favor composition over inheritance", and go with

public class EasyLocation {

    Location loc;

    public EasyLocation(Location loc) {
        this.loc = loc;
    }

    public long getElapsedTime() {
        return getTime() - System.currentTimeMillis();
    }

    public Location getLocation() {
        return loc;
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜