我想对 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);
}
}
将被翻译成这个标准的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));
}
}
是否有一些好的和安全的方法可以像编写自己的编译器一样更容易地扩展 java 语法?
(我的意思不仅是运算符重载,而且本质上是扩展 java 语法的好方法。)