如何在 Java 中调用替代静态构造函数?

How do you invoke an alternative static constructor in Java?

如何在 Java 中调用这些替代静态构造函数?

我想使用 newFromLatLong 格式创建 Location 对象,但不知道如何

public class Location {

    public final double x;
    public final double y;

    public Location(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public static Location newFromPoint(Point point, Location origin,
            double scale) {
        return new Location(point.x / scale + origin.x, origin.y - point.y
                / scale);
    }

    
    public static Location newFromLatLon(double lat, double lon) {
        double y = (lat - CENTRE_LAT) * SCALE_LAT;
        double x = (lon - CENTRE_LON)
                * (SCALE_LAT * Math.cos((lat - CENTRE_LAT) * DEG_TO_RAD));
        return new Location(x, y);
    }

你有创建对象的静态方法,所以你在 class 本身上调用它们,这将 return 你一个 Location 对象。您可以将其用于其他用途。

Location location = Location.newFromLatLon(1.1, 1.2);

考虑使用构建器模式来创建 Location 对象。为了避免重复代码,我推荐使用 Lombok @Builder 注解:

https://projectlombok.org/features/Builder

此外,考虑到您正在使用相同的 Location 对象作为 newFromPoint 方法的参数:


public static Location newFromPoint(Point point, Location origin,
            double scale) {
        return new Location(point.x / scale + origin.x, origin.y - point.y
                / scale);
}

也许您需要查看您的域定义。