parsecer
parsecer

Reputation: 5106

How to use function parameter: call specific getter

I have a Dog class with a name and a breed. I want to print either the dog's name or its breed depending on a method parameter passed to a printDog method. How do I do that?

class Dog  {
  private String name;
  private String breed;

  //constructor

  public String getName()  {
    return name;
  }

  public String getBreed()  {
    return breed;
  }
}
public void printDog(Dog dog, ?)  {
  System.out.println(dog.?);
}
Dog dog = new Dog("Buster", "Shepherd");
printDog(dog, dog::getName);
printDog(dog, dog::getBreed);

Upvotes: 1

Views: 45

Answers (1)

Sweeper
Sweeper

Reputation: 272760

Use a Function<Dog, String>. This represents a function that takes a Dog and returns a String.

public void printDog(Dog dog, Function<Dog, String> propertySelector)  {
  System.out.println(propertySelector.apply(dog));
}

You can call this exactly the way you wanted:

Dog dog = new Dog("Buster", "Shepherd");
printDog(dog, dog::getName);
printDog(dog, dog::getBreed);

Upvotes: 5

Related Questions