簡體   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