Java8 using enum values ​​in default interface methods

I am exploring the possibilities of static and standard methods introduced in java 8.

I have an interface that has two default methods that create a command that I run on the server via ssh in order to remotely perform some simple tasks. Moving the mouse requires 2 arguments: the x and y positions of the mouse.

public interface Robot {

    default String moveMouse(int x, int y) {
        return constructCmd("java -jar move_mouse.jar " + x + " " + y);
    }

    default String clickLeft() {
        return  constructCmd("java -jar click_left.jar");
    }

    static String constructCmd(String cmd) {
        return "export DISPLAY=:1.0\n" +
                "cd Desktop\n" +
                cmd;
    }
} 

I have several enumerations with predefined values, I could combine all the enumerations into one, and not use the interface, whatever that is, however this enumeration will contain hundreds or thousands of values, and I want it to be organized somewhat , ve split evertying in a few listings.

, , , .

public enum Field implements Robot {

    AGE_FIELD(778, 232),

    NAME_FIELD(662, 280);

    public int x;
    public int y;

    Field(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

, String:

Field.AGE_FIELD.clickLeft();
Field.AGE_FIELD.moveMouse(Field.AGE_FIELD.x, Field.AGE_FIELD.y);

moveMouse , , enum.

- ?

+4
2

. , , ( Robot). , Robot . , MouseTarget ( ):

public interface MouseTarget {
    public int getTargetX();
    public int getTargetY();

    public default void moveMouseHere(Robot robot) {
        robot.moveMouse(this.getTargetX(), this.getTargetY());
    }
}

. , moveMouseHere(Robot robot) , Robot ( ). , , - Fields :

public enum Fields implements MouseTarget {

    AGE_FIELD(778, 232), NAME_FIELD(662, 280);

    public int targetX;
    public int targetY;

    Fields(int targetX, int targetY) {
        this.targetX = targetX;
        this.targetY = targetY;
    }

    @Override
    public int getTargetX() {
        return (this.targetX);
    }

    @Override
    public int getTargetY() {
        return (this.targetY);
    }
}
+4

Robot, , , Robot Robot, .

Field

public enum Field {

    ...

    public String moveMouse(Robot robot) {
        return robot.moveMouse(x, y);
    }

    public String clickLeft(Robot robot) {
        return robot.clickLeft();
    }
}

, .

+2

Source: https://habr.com/ru/post/1658906/


All Articles