繁体   English   中英

访问私有内部类中的公共方法

[英]Accessing public methods in private inner classes

我有以下代码,我想知道如何访问public method:locationFinderprivate inner class:LocationBasedFormatterouter class:LocationFormatter

基本上我想从MyClass访问方法locationFinder并获取List<String>

@Getter
@Setter
public class LocationFormatter {

    public static final Formatter Location(String longitute, String latitude) {
        return new LocationBasedFormatter(longitute, latitude)
    }

    public static interface Formatter {}

    @AllArgsConstructor
    private static final class LocationBasedFormatter implements Formatter {
        private String longitute;
        private String latitude;

        public final List < String > locationFinder() {
            String location = "Your Long: " + this.longitute + " Your Lat: " + this.latitude;
            List < String > randomList = new ArrayList < String > ()
            randomList.add(location)
            return randomList;
        }

    }
}

以下是我需要传递值并访问locationFinder方法的其他主要 class :

public class MyClass {
    public static void main(String args[]) {
        LocationFormatter loc = new LocationFormatter();
        LocationBasedFormatter result = loc.Location("44.54", "94.54");
    }
}

当我尝试在locresult上查找 Objects/Methods 时,我无法找到我的 Method locationFinder 我想访问locationFinder方法并根据我传递给我的私有变量的值获取List

我有点困惑,无法在另一个 class 中获得该方法。 但是,如果我在同一个 class 中编写主要方法,那么我可以访问它。

看来您需要在接口Formatter中声明方法locationFinder并使用此接口(目前只是一个标记接口)而不是其在私有 class 中的具体实现:

public static interface Formatter {
    List<String> locationFinder();
}

那么这个方法就可以公开访问了:

public class MyClass {
    public static void main(String args[]) {
        // no need to instantiate LocationFormatter, Location is static method
        Formatter result = LocationFormatter.Location("44.54", "94.54");

        List<String> locationList = result.locationFinder();
    }
}

但是,此代码中的类和方法应使用更具描述性的名称。

从技术上讲, LocationBasedFormatter不是内部 class。 这是一个static 嵌套 class。

LocationFormatter class 中添加public static getLocationBasedFormatterInstance()方法。 这个getLocationBasedFormatterInstance()可以返回LocationBaedFomratter的实例

public class LocationFormatter {
  ... 
  public static getLocationBasedFormatterInstance(){
     LocationBasedFormatter lbf = new LocationBasedFormatter();
     return lbf;

  }

}

然后,您必须从您的 main 方法创建 static 嵌套 class LocationBasedFormatter的 object 。

LocationFormatter.LocationBasedFormatter locationFormatter = new LocationFormatter();
LocationBaedFomratter loationBasedFomratter = locationFormatter.getLocationBasedFormatterInstance();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM