Advertisement
Guest User

ABG

a guest
Aug 5th, 2014
574
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. Advanced Bounding with Generics (in Java)
  2.  
  3. Let’s say we have the following method in Java:
  4.  
  5. public String generateNickname(? name) { /* */ }
  6.  
  7. We want this method to take in a name and return a nickname as a String. We could use a String as the name.
  8.  
  9. public String generateNickname(String name) { /* */ }
  10.  
  11. This could work, but we might want more information. We might want an object with a method for setting the nickname to the new nickname or a method for checking to see if the object already has a nickname. We could create a Nameable interface.
  12.  
  13. public interface Nameable {
  14.  
  15. public String getName();
  16. public String getNickname();
  17. public String setNickname(String nickname);
  18. public default boolean hasNickname() {
  19. return !getName().equals(getNickname());
  20. }
  21. }
  22.  
  23. Now, we can write the method to use the Nameable interface.
  24.  
  25. public String generateNickname(Nameable name) { /* */ }
  26.  
  27. However, this does not work with any class that we don’t define. Any class in the Java API or any third party API will not use the Nameable interface we just created. What we need is a way to get any object of any class that has the methods we need. We can use a type parameter with the brand new advanced bounding feature to accomplish this.
  28.  
  29. public <O containsMethod String getName()> String generateNickname(O name) { /* */ }
  30.  
  31. What this does is say that the type parameter O must contain a method that is called getName, takes no parameters, returns a String, and is accessible. The name object would now have access to all of the Object methods as well as the getName() method.
  32.  
  33. Let’s try to extend this idea. The Nameable interface also has a setNickname() method. Let’s change this code to call the method instead of returning a String.
  34.  
  35. public <O containsMethod String getName() && containsMethod void setName(String)> void generateNickname(O name) { /* */ }
  36.  
  37. The O type parameter for this method now must define a String getName() and a void setName() that takes a String parameter. We can now call name.setNickname() within the method because we are bounding O such that it must contain this method.
  38.  
  39. These are basic examples of this idea. More bounds could be added, like containsField or containsAnnotation.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement