Java:如何限制方法对特定类的访问? [英] Java: How to limit access of a method to a specific class?

查看:192
本文介绍了Java:如何限制方法对特定类的访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个例子:

class A 
{
   List l = new List ();
   list.insert("x");
}

class List
{
   ...
   public void insert ()
   {
      /*insertion occurs*/
   }
   ...
}

在所有保持insert()方法public,但限制访问只有类A,以便没有其他类可以访问它,只有当从A调用

Is it possible at all to keep the insert() method public, but limit access only to class A so that no other class can access it, only when called from A?

推荐答案

如果方法是公开的,每个人都可以访问它。访问控制类似于你的技巧是通过一个接口公开一组公共操作,向实现接口的私有类添加辅助操作,并让用户程序到接口,而不是类。

If the method is public, everyone can access it. The trick to access control like yours is to expose a set of public operations through an interface, add auxiliary operations to a private class implementing the interface, and make your users program to the interface, not to a class.

下面是一个例子:

public interface MyList {
    Object elementAt(int i);
}
public class A {
    private static class MyListImpl implements MyList {
        public Object elementAt(int i) {
            ...
        }
        public void insert(Object element) {
            ...
        }
    }
    private final MyListImpl list = new MyListImpl();
    public MyList getList() { return list; }
    public void insert(Object o) { list.insert(o); }
}

使用方案:

A a = new A();
a.insert(123);
a.insert("quick brown fox");
MyList lst = a.getList();
System.out.println(lst.elementAt(0));
System.out.println(lst.elementAt(1));

这篇关于Java:如何限制方法对特定类的访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆