为什么我不能实例化LocationManager类?

时间:2014-04-24 19:58:16

标签: java android access-control

我正在尝试使用LocationManager类进行一些工作,并发现我无法实例化它。

它不是一个抽象类,我的印象是只有标记为抽象的类才能被实例化。

1 个答案:

答案 0 :(得分:2)

要获得更完整的答案:

如果你看一下source code for LocationManager,特别是第303行,你会发现它实际上 有一个公共构造函数......但是有一个特殊的注释:

/**
 * @hide - hide this constructor because it has a parameter
 * of type ILocationManager, which is a system private class. The
 * right way to create an instance of this class is using the
 * factory Context.getSystemService.
 */
public LocationManager(Context context, ILocationManager service) {
    mService = service;
    mContext = context;
}

@hide注释使构造函数远离Javadoc,IDE无法显示它。你可以read more about the @hide annotation in this SO Q and A

基本上,这个类的设计是为了让你从Context得到它而不是自己实例化它。对于需要复杂(或特定于平台)配置的事物,这是一种相当常见的设计,您希望避免让用户处理。

请注意,@hide注释及其处理特定于Android。

这类似于Builder或Factory模式的工作方式,其中只有构建器/工厂类可以实例化对象,尽管通常用Java中的私有或包私有构造函数完成:

public class MyWidget
{
    private final Foo someObject; 
    // ... more stuff


    private MyWidget(Builder builder)
    {
        this.someObject = builder.someObject;
        // ... more stuff
    }

    public static class Builder
    {
        Foo someObject;

        public Builder() {}

        public Builder withFoo(Foo someObject)
        {
            this.someObject = someObject;
            return this;
        }

        public MyWidget build()
        {
            return new MyWidget(this);
        }
    }
}

将其调用为:

MyWidget widget = new MyWidget.Builder().withFoo(someFoo).build();