开发者

Java insuring that an object passed to a method extends a given class

What would be the best way to check in an object being passed into a method extended a given class?

Currently i have a method that takes a ByteBuffer of data to send and a 'player' class that i wr开发者_如何学Pythonote, and queues the data up on the IO server to be sent to the client:

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

What i would like to be able to do is let the player object passed in be any object that extends the player class. I have done some searches and found something like this:

public void send(ByteBuffer toSend, Player<? extends Player> player)
{   
   // prep the byte buffer for sending, and queue it on the IO server
}

But that is giving me compile errors, and i don't understand exactly whats going on. Would this be the proper way to do this? And if so, could anyone explain what this code is specifically doing and why it isn't working and or link me to an article that explains this in greater detail.

Alternatlly, I suppose i could set it up something like this:

public void send(ByteBuffer toSend, Object player)
{
  // Check that the player extends Player, using instanceof or something 
  // along those lines   

  // Prep the ByteBuffer, and queue the data to send
}

However, that code feels kind of brittle to me, compared to the above code.

Any help is most welcome. Thanks :)


If I am not mistaken, you can keep the first syntax (expecting a Player object) and it would work with any sub-class of Player. That's polymorphism.


Your current definition of send already accepts any subclass of Player (or implementation, if you later decide to make Player an interface).


Currently your method will accept any subclass of Player (if you use the first method). But if you wanted to do this with an interface (to ensure that specific methods are implemented and that you can call them), you can try genericizing the class and do something like this:

public class MyClass<T extends PlayerInterface> {
   public void send(ByteBuffer toSend, T player) {    
      // prep the byte buffer for sending, and queue it on the IO server
   }  
}

But that might be overkill. In this case you might be better off just using an interface as a paramter:

public void send(ByteBuffer toSend, PlayerInterface player) {    
   // prep the byte buffer for sending, and queue it on the IO server
}  


You first method is fine.

public void send(ButeBuffer toSend, Player player)
{
  // prep the byte buffer for sending, and queue it on the IO server
}

It insures that only objects of type Player (or objects that extend Player) are valid parameters..

I would recommend using interfaces to define what is allowed an what is not allowed as a parameter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜