java - 访问私有内部类中的公共方法
问题描述
我有以下代码,我想知道如何访问public method:locationFinder
.private inner class:LocationBasedFormatter
outer class:LocationFormatter
基本上我想访问该方法并locationFinder
获取MyClass
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
方法的另一个主类:
public class MyClass {
public static void main(String args[]) {
LocationFormatter loc = new LocationFormatter();
LocationBasedFormatter result = loc.Location("44.54", "94.54");
}
}
当我尝试找到 Objects/Methods onloc
或result
然后我无法找到我的 Method locationFinder
。我想访问locationFinder
方法并List
根据我传递给我的私有变量的值来获取。
我有点困惑,无法在另一个类中获取该方法。但是,如果我在同一个类中编写 main 方法,那么我可以访问它。
解决方案
看来您需要locationFinder
在接口中声明方法Formatter
并使用该接口(目前只是一个标记接口)而不是其在私有类中的具体实现:
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();
}
}
但是,此代码中的类和方法应使用更具描述性的名称。
推荐阅读
- go - 如何通过 http.ServeMux 在 GoLang lang 中使用 swaggo (swagger doc)?
- visual-studio - Visual Studio 2017 Enterprise 的一部分安装在 C 盘上
- python - 通过汉明距离找到最近的子串
- linux - 使用其独特的命令行捕获从终端启动的进程的 pid
- asp.net-core - 如何在 ASP.NET Core 中的请求之间获得独立的 JSON 引用解析?
- jakarta-ee - 如果某些注入的属性发生更改,则重新注入 CDI bean
- python - 在一小时后 X 分钟时中断请求流
- r - 未列出数据框产生意外结果
- ruby-on-rails - Rails 查询对象未加载
- reactjs - 第一次测试运行时未创建快照