[英]Accessing public methods of a Private Inner Class, from outside the Enclosing class
[英]Accessing public methods in private inner classes
我有以下代碼,我想知道如何訪問public method:locationFinder
在private inner class:LocationBasedFormatter
的outer 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");
}
}
當我嘗試在loc
或result
上查找 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.