一种扩展java语法的简单方法

Avr*_*gon 1 java preprocessor

我想在java语法中进行一些更改.例如,我想使用运算符'+'来添加向量.所以我想要这个代码:

public class Vector2 {
    public float x, y;
    public Vector2(float x, float y) {this.x = x;this.y = y;}
    public String toString() {...}

    public static Vector2 operator+(Vector2 a, Vector2 b) {
        return new Vector2(a.x + b.x, a.y + b.y);
    }

    public static void main(String[] args) {
        Vector2 a = new Vector2(3, 6);
        Vector2 b = new Vector2(2, 8);
        System.out.println(a + b);
    }
}
Run Code Online (Sandbox Code Playgroud)

将被转换为这个标准的java代码:

public class Vector2 {
    public float x, y;
    public Vector2(float x, float y) {this.x = x;this.y = y;}
    public String toString() {...}

    public static Vector2 operator_plus(Vector2 a, Vector2 b) {
        return new Vector2(a.x + b.x, a.y + b.y);
    }

    public static void main(String[] args) {
        Vector2 a = new Vector2(3, 6);
        Vector2 b = new Vector2(2, 8);
        System.out.println(Vector2.operator_plus(a, b));
    }
}
Run Code Online (Sandbox Code Playgroud)

在编写自己的编译器时,是否有一些更好,更安全的方法来扩展java语法?

(我的意思不仅是运算符重载,而且基本上是扩展java语法的好方法.)

Oma*_*aha 6

由于Java不支持运算符重载,如果您真的需要该语法,则需要更改语言.