我正在嘗試編寫接受功能接口的通用方法。看例子。任何幫助讚賞。通用功能接口使用消費者的簡單示例
更新:有編譯和運行。對意見或建議有興趣改進或澄清。
我不會創建一個類型化的抽象基類。向repeat方法中添加一個附加參數,指定執行命令的機器人似乎與其他類似示例更加一致。
想法?
import java.util.function.Consumer;
/**
* The intent is to create a generic function repeat() in the Robot base class
* that will repeat actions for all subclasses of robots
*/
public class GenericFunctionalInterface
{
public static void main(String[] args)
{
// Consumer<Robot> actionTurn = Robot::turnLeft;
// Consumer<EnhancedRobot> anyAction = EnhancedRobot::anyAction;
Robot r = new Robot();
r.repeat(3, a->a.turnLeft());
EnhancedRobot e = new EnhancedRobot();
e.repeat(3, a->a.anyAction()); // cannot find symbol - method anyAction()
// if ((EnhancedRobot)a).anyAction() is used this works
}
}
class Robot
{
public void move() { System.out.println("MOVE"); }
public void turnLeft() { System.out.println("TURNLEFT"); }
public <T extends Robot> void repeat(int n, Consumer<T> cmd)
{
for(int i=0; i<n; i++) cmd.accept((T) this); // UPDATED: casting this to T removed -> incompatible types: Robot cannot be converted to T
// this will be whatever type repeat is called on
}
// added this override - specifying what robot to send the command to
public <T extends Robot> void repeat(int n, Consumer<T> cmd, T robot)
{
for(int i=0; i<n; i++) cmd.accept(robot);
}
}
class EnhancedRobot extends Robot
{
public void turnRight() { System.out.println("TURNRIGHT"); }
public void move() { System.out.println("MOVEOVERIDE"); }
public void anyAction() { System.out.println("ANYACTION"); }
}
確定。如果我理解正確,這應該工作: public void repeat(int n,Consumer cmd,T robot) {int i = 0; i a.anyAction(),e); –
Americano
是的,自從您聲明'消費者'和'機器人'具有相同類型後,它就可以工作。您可以使該方法爲靜態,因爲它可以與另一個「Robot」實例一起使用。 –