首页 > 解决方案 > 访问私有内部类中的公共方法

问题描述

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

基本上我想访问该方法并locationFinder获取MyClassList<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 onlocresult然后我无法找到我的 Method locationFinder。我想访问locationFinder方法并List根据我传递给我的私有变量的值来获取。

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

标签: javamethodsinner-classesprivate-methods

解决方案


看来您需要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();
    }
}

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


推荐阅读